- Home /
The question is answered, right answer was accepted
Determining if a variable is even or odd?
Hello. If I have a variable is a whole number, how can I set up and if statement to see of the variable is even or odd? such as:
if (TEST==odd ){something};
if (TEST==even){something else};
Thanks
Answer by Tseng · Mar 08, 2012 at 02:28 AM
Use modulo operator
if(test%2==0) // Is even, because something divided by two without remainder is even, i.e 4/2 = 2, remainder 0
if(test%2==1) // Is odd, because something divided by two with a remainder of 1 is not even, i.e. 5/2 = 2, remainder 1
what if a dividend is negative? He said the variable is a whole number.
Very simple, thanks.
if(test%2==1||test%2==-1) Can I use this too?
Just use test%2==0 for even or test%2!=0 for uneven. However, this only works in this special case or if you want deter$$anonymous$$e if a number is fully dividable through another number or not.
in the strange case anyone wanted to see if a float is odd or even, first I would cast it to an int. It makes more sense to me, but some people might still prefer the strange case in which a float is perfectly dividable.
Hi, in my case its very useful because im making a runner where the player can only move to certain positions. Those positions are even coordinates and i only want the player to move when they are in an even position, otherwise they could move in the middle of the lines.
Answer by firemyst · Jan 16, 2014 at 01:12 PM
Here’s a blog article which benchmarks quite a few ways to test if a number is odd or even.
Surprisingly, the fastest way appears to be the modulus % operator, even out performing the bitwise ampersand &, as follows:
for (int x = 0; x < NumberOfNumbers; x++)
{
if (x % 2 == 0)
total += 1; //even number
else
total -= 1; //odd number
}
Definitely worth a read for those that are curious.
Follow this Question
Related Questions
How to convert Python in to C#? Maths or find Shortest distance between two skew lines in 3D space. 1 Answer
How do i get the part of a float after the point? 7 Answers
Casting-related error: "^ cannot be applied to double and int" 1 Answer
getting the lowest point of a sine wave in javascript 3 Answers