我正在尝试创建一个DisplayAverage子过程,该过程接受3个整数作为参数。此过程应找到这3个数字的平均值,并在列表框中显示数字及其平均值。我知道我在这里做错了什么我只是想弄清楚是什么。
Private Sub btnAverage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAverage.Click
Dim a As Integer = CInt(txtone.Text)
Dim b As Integer = CInt(txtTwo.Text)
Dim c As Integer = CInt(txtThree.Text)
Dim average As Double
average = (a + b + c) / 3
lstOutput.Items.Add(average.ToString())
End Sub
Sub DisplayMyName()
lstOutput.Items.Add("David Whitney")
End Sub
Sub DisplayAverage()
Dim a As Integer = CInt(txtone.Text)
Dim b As Integer = CInt(txtTwo.Text)
Dim c As Integer = CInt(txtThree.Text)
Dim average As Double
average = (a + b + c) / 3
lstOutput.Items.Add("The average of " & a & " and " _
& b & " and " & c & " is " & average)
End Sub
Private Sub btnAve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAve.Click
lstOutput.Items.Clear()
DisplayMyName()
Dim a As Integer = CInt(txtone.Text)
Dim b As Integer = CInt(txtTwo.Text)
Dim c As Integer = CInt(txtThree.Text)
Dim average As Double
average = (a + b + c) / 3
lstOutput.Items.Add(average.ToString())
DisplayAverage()
End Sub
结束班
答案 0 :(得分:1)
你有代码可以多次写出平均值。你真正需要做的就是:
Private Sub btnAve_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAve.Click
lstOutput.Items.Clear()
lstOutput.Items.Add("David Whitney")
Dim a,b,c As Float
Try
a = Convert.ToSingle(txtone.Text)
b = Convert.ToSingle(txtTwo.Text)
c = Convert.ToSingle(txtThree.Text)
Catch ex As FormatException
MessageBox.Show("Please enter a valid number for a, b, and c.", "Error")
Exit Sub
End Try
Dim average As Double = (a + b + c) / 3
lstOutput.Items.Add("The average of " & a & " and " _
& b & " and " & c & " is " & average)
End Sub
答案 1 :(得分:0)
我同意Chris你在一个地方需要代码,但我不会在按钮点击事件中拥有它。将它放在自己的例程中,称为平均值或类似值。
而且,如果您使用的是.NET Framework 3.5,那么有一种更好的平均数字方法...... LINQ。你可以在这里找到基础知识: http://tinyurl.com/bd2zcq
LINQ方法的好处是你可以根据需要平均尽可能多的数字,因此算法具有很好的重用性。也许是帮助班?