2012-11-09 112 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