如何获得方程式的特定代码

时间:2019-05-04 16:21:34

标签: vb.net visual-studio-2019

我是在Visual Studio 2019中使用Visual Basic处理我的第一个应用程序的初学者。

我要计算这个:

enter image description here

我在(列表视图)和(文本框)中都拥有W i
我在列表视图中所有H i

我的问题是我如何将w i 列表视图(或W i 文本框)乘以h i 列表视图,得到这个导致第三个列表视图?

1 个答案:

答案 0 :(得分:0)

我希望您发现的最大问题是从ListViews获取数据-请注意,使用控件存储数据通常不是一个好主意。

请注意,VB.NET(以及C#和许多其他计算机语言)中的数组索引从零开始(即,它们是偏移量,而不是数学中使用的索引)。

一旦将数据存储在数组中,就很容易执行计算。为方法和变量想出有意义的名称也是一个问题。

有了名为ListViewW,ListViewH和ListViewF的ListView,我想到了:

Public Class Form1
    Dim rand As New Random()

    Function Fvalues(Fb As Double, weights As Double(), values As Double()) As Double()
        If weights.Length <> values.Length Then
            Throw New ArgumentException("Number of weights does not equal number of values.")
        End If
        'TODO: Possibly more argument checking.

        Dim total = 0.0
        For i = 0 To weights.Length - 1
            total += weights(i) * values(i)
        Next
        'TODO: Check for total = 0.

        Dim F(weights.Length - 1) As Double

        For i = 0 To weights.Length - 1
            F(i) = Fb * weights(i) * values(i) / total
        Next

        Return F

    End Function

    Function ListViewToDoubles(lv As ListView) As Double()
        Dim d As New List(Of Double)

        For i = 0 To lv.Items.Count - 1
            Dim dbl As Double
            If Double.TryParse(lv.Items(i).Text, dbl) Then
                d.Add(dbl)
            End If
        Next

        Return d.ToArray()

    End Function

    Sub CreateSampleData()
        For i = 1 To 5
            ListViewW.Items.Add(rand.NextDouble().ToString())
            ListViewH.Items.Add(rand.Next(0, 11).ToString())
        Next

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        CreateSampleData()

        Dim weights = ListViewToDoubles(ListViewW)
        Dim values = ListViewToDoubles(ListViewH)

        Dim f = Fvalues(0.5, weights, values)

        For Each x In f
            ListViewF.Items.Add(x.ToString())
        Next

    End Sub

End Class