2011-12-28 49 views
1

我有一個包含一些數字的數據集,我想計算數字差異的總和,我該怎麼做? 例如我的數據集是這樣的:計算vb.net for循環中數字差異的總和

名稱分數

路100

亞當90

詹姆斯80

彼得·70

邁克·60

如何我計算嗎?在vb.net的「for循環」內差異的總和,以便它做如下的事情:

(100-90)+(90-80)+(80-70)+(70​​- 60)= 40

我想下面這樣做,但我不知道如何添加的區別:

Dim i as integer 
For i = 0 to ds.tables(0).rows.count 
    ds.tables(0).Row(i).Item(1) 
    Dim diff = ds.tables(0).Row(i).Item(1) - ds.tables(0).Row(i+1).Item(1) 
    sum = .... 
Next 

任何幫助將不勝感激

+0

Joelrobichaud,我編輯了我的問題。謝謝! – Dee 2011-12-28 03:10:46

回答

2

你可以試試這個,

Dim totalValue As Integer = 0 

    For index = 1 To ds.Tables(0).Rows.Count 
     totalValue += (CInt(ds.Tables(0).Rows(index - 1).Item(1)) - CInt(ds.Tables(0).Rows(index).Item(1))) 
    Next 

您可以用總價值爲你的答案

0

首先,你需要停止在達到計數之前循環,否則您將收到異常。

其次,你需要添加一個特殊的情況下的第一個項目:

' The sum of the differences 
Dim wSumOfDifferences As Integer 
' Start with a non-sensical value for the last value that we processed 
Dim wLastValue As Integer = -1 

For Each oRow As DataRow in ds.Tables(0).Rows 
    Dim wCurrValue As Integer 

    ' Get the current value 
    wCurrValue = CInt(oRow.Item(1)) 

    ' If we are not working on the first item, calculate the difference between 
    ' the current value and the last value 
    If wLastValue <> -1 Then 
     wSumOfDifferences += (wLastValue - wCurrValue) 
    End If 

    ' Record the current value as the last value 
    wLastValue = wCurrValue 
Next 

Console.WriteLine("Sum = " & CStr(wSumOfDifferences))