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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With