2012-11-09 69 views
0

嗨,我想在vb.net中创建一个程序,找到一个数字的平均值只使用一个变量的值与inputbox和第二个计数应该是负数,但我不能得到准确的answere 这里是代码如何在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 
+1

你能使用前退出循环一个'list(of integer)'而不是'in teger',以保存用户给出的值。然后,您可以在列表中保存用户给出的值的总和。只给你2个变量。我可以将一些示例代码放在一起,但我不熟悉'inputbox'表单工具,并确定为什么需要num> 0。 – Pezzzz

回答

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 
+0

感谢您的解决方案,它现在正在工作 –

+1

记住要测试以确保数字实际上是一个数字而不是一个字符串。例如通过:'Integer.TryParse'等 –

+0

高兴地帮助你Syed,我的代码没有优化...循环(while)不应该检查num(> = 0),因为我们退出使用临时LOL ... Stuart,ty代码!,我只是想输入字符串,然后转换它(使用Val())... – Krofz

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