我有一个包含一些数字的数据集,我想计算数字差异的总和,我该怎么做? 例如,我的数据集如下所示:
名称得分
Luke 100
Adam 90
詹姆斯80
彼得70Mike 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 :(得分: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
您可以使用totalValue作为答案
答案 1 :(得分: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))