How to get even or odd numbers

49,531

Solution 1

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.

Solution 2

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.

Share:
49,531
Didy
Author by

Didy

Updated on April 26, 2020

Comments

  • Didy
    Didy about 4 years

    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