1

嗨,我正在尝试在 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
4

2 回答 2

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
于 2012-11-09T06:44:56.650 回答
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
于 2012-11-09T06:45:20.597 回答