2011-12-28 78 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))