Reputation: 85
I don't know why this program doesn't works. I get a random number and the computer select what type it is even or odd ?
Dim a As New Random()
Dim b As Integer
Dim ca As Integer
b = a.Next(0, 10)
Debug.Print(b)
ca = b / 2
If ca = 0 Then
Debug.Print("Even")
Else
Debug.Print("Odd")
End If
Upvotes: 4
Views: 57961
Reputation: 1
Private sub command1_click()
Dim a as integer
a = text1.text
If a mod 2=0 then
Print a & " is even"
Else
Print a & "is odd"
Endif
End sub
Upvotes: 0
Reputation: 11773
You could also just check the low order bit, if it is on the number is odd, if it is off the number is even. Using a function:
Dim a As New Random()
Dim b As Integer
b = a.Next(0, 10)
Debug.WriteLine(b)
If isEven(b) Then
Debug.WriteLine("even")
Else
Debug.WriteLine("odd")
End If
Private Function isEven(numToCheck As Integer) As Boolean
Return (numToCheck And 1) = 0
End Function
edit: might be faster than mod but haven't checked.
Upvotes: 7
Reputation: 23937
You are messing up your operators.
You use division /
, but you want to use the modulo operator Mod
.
Please note: in C# it is %
. In VB.Net it is Mod
Reference: http://msdn.microsoft.com/en-us/library/se0w9esz(v=vs.100).aspx
Dim a As New Random()
Dim b As Integer
Dim ca As Integer
b = a.Next(0, 10)
Debug.Print(b)
ca = b Mod 2
If ca = 0 Then
Debug.Print("Even")
Else
Debug.Print("Odd")
End If
Why your code does not work as expected:
The culprit is indeed your if-statement. You are checking if the result of b / 2
is 0. But this can only be true if b
itself is 0. Every number greater then 0 devided by half is greater then zero.
Your code looks like you want to check for the rest of a division, hence the solution with the modulo operator.
Upvotes: 16