Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get even or odd numbers

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
like image 257
Didy Avatar asked Nov 29 '22 00:11

Didy


2 Answers

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.

like image 131
Marco Avatar answered Dec 09 '22 13:12

Marco


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.

like image 29
dbasnett Avatar answered Dec 09 '22 13:12

dbasnett