如何在vb.net中找到平均值

时间:2012-11-09 06:29:49

标签: vb.net

您好我正在尝试在vb.net中创建一个程序,使用输入框仅使用一个变量值来查找数字的平均值,而计数数字的第二个应该是负数但我无法获得准确的答案 这是代码

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim num, count As Integer
    num = InputBox("Please enter number") 'for first entry
    While num > 0    ' here we have to check it that the num is not negative then to start
        num = InputBox("Please enter number")
        num += num
        count += 1             'this will calculate how many times number added    
    End While
    MsgBox("Average is " & num / count)


End Sub

2 个答案:

答案 0 :(得分:2)

使用此代码...我仍然需要临时变量,因为在退出循环之前,该值不应该在

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim num, count As Integer
    count = 0
    num = 0
    While num >= 0    ' here we have to check it that the num is not negative then to start
        Dim temp As Integer
        temp = InputBox("Please enter number")
        If temp < 0 Then
            Exit While
        End If
        count += 1             'this will calculate how many times number added 
        num += temp
    End While
    MsgBox("Average is " & (num / count))
End Sub

答案 1 :(得分:1)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)        Handles Button1.Click
Dim num, count, avg As Integer
num = InputBox("Please enter number") 'for first entry
While num > 0    ' here we have to check it that the num is not negative then to start
    avg += num
    count += 1             'this will calculate how many times number added    
    num = InputBox("Please enter number")
End While
    MsgBox("Average is " & avg / count)
End Sub