【问题标题】:Calculating the sum of number difference within a for loop in vb.net计算vb.net中for循环内的数差总和
【发布时间】:2011-12-28 12:12:30
【问题描述】:

我有一个包含一些数字的数据集,我想计算数字差的总和,我该怎么做? 例如我的数据集如下所示:

姓名分数

卢克 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

任何帮助将不胜感激

【问题讨论】:

  • Joelrobichaud,我已经编辑了我的问题。谢谢!

标签: vb.net for-loop


【解决方案1】:

你可以试试这个,

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 作为您的答案

【讨论】:

    【解决方案2】:

    首先,你需要在到达计数之前停止循环,否则你会收到一个异常。

    其次,需要为第一项添加特殊情况:

    ' 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 2017-12-16
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多