使程序忽略一个数字

时间:2015-02-10 09:55:02

标签: vb.net

我有一个程序可以确定一个数字是奇数还是偶数,并带有适当的标签来说明总数是多少,还有一个计数器,但我需要帮助试图让程序忽略0,因为当你在程序中输入它时,它的意思是完成,但也将其视为偶数,并将其添加到EvenCount,谢谢!

Public Class Form1
Dim Num, Decider, Oddcount, Oddtotal, Evencount, Eventotal As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Do
        Num = InputBox("Please enter whole number")
        Decider = Num Mod 2
        If Decider > 0 Then
            MessageBox.Show("Odd")
            Oddcount += 1
            Oddtotal += Num
        Else
            MessageBox.Show("Even")
            Evencount += 1
            Eventotal += Num
        End If

    Loop Until Num = 0
    LabelOdd.Text = Oddtotal
    LabelEven.Text = Eventotal
    LabelEvenCount.Text = Evencount
    LabelOddCount.Text = Oddcount
End Sub End Class    

1 个答案:

答案 0 :(得分:2)

如果要忽略零,最好使用Do..While语句,该语句在进入循环之前评估条件。

Public Class Form1

Dim Num, Decider, Oddcount, Oddtotal, Evencount, Eventotal As Integer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

  Num = 1 ' Initialised to force in step into loop
  Do While Num <> 0
        Num = InputBox("Please enter whole number")

       ' Recheck the value inserted - if zero, break.
       If Num = 0 Then  Exit While 

        Decider = Num Mod 2
        If Decider > 0 Then
            MessageBox.Show("Odd")
            Oddcount += 1
            Oddtotal += Num
        Else
            MessageBox.Show("Even")
            Evencount += 1
            Eventotal += Num
        End If
  Loop

  LabelOdd.Text = Oddtotal
  LabelEven.Text = Eventotal
  LabelEvenCount.Text = Evencount
  LabelOddCount.Text = Oddcount
End Sub End Class