Loading...
Logo
Processing Forum
I feel like there's an easy answer to this problem but for some reason it's alluding me.

Here's the problem:
if number x is an even number, then do this thing.
if number x is an odd number (or not an even number), don't do that thing.

simple boolean question. My problem is that I can't think of a way to represent even and odds as a property in processing. So I tried to define even and odd numbers:
Even numbers are numbers that when divided by 2 yield a whole number.
Odd numbers are numbers that when divided by 2 yield fractional numbers.


Copy code
  1. int x;
    float x;
    boolean a = false;

           /*I know you can't do this but...I'm trying, essentially, to ask is x an integer (whole number) or float (fractional             number). I was thinking about trying to use %, but I'm scared of it:
          
                 float || int r = random (100); ?? */

                if ( r / 2 = int){
                      stroke (255);
                      } else {
                            noStroke;
                      }
                }


Does that^ make any sense at all? Can anyone help me figure out the whole odd/even thing?

Replies(2)

you want to use the modulus operator. (%) it will return the remainder of what would happen if the left number is divided by the right. ex 5 % 2 = 1 and thats how u know that 5 is odd. Any number %2 is even if the result is 0 and odd if the result is 1. so in ur situation

Copy code
  1.   int r = random (100);
  2. if(r %2 == 0){
  3.       // its even
  4. }else{
  5. // its odd
  6. }   
though random numbers will most likely return floats so you will need to change that line to an int using the round(), floor(), or ceil(). Round will round (.5 or higher rounds up, less than .5 rounds down), floor() rounds down no matter what and ceil() rounds up no matter what. so example:

Copy code
  1. int r = round(random(100));
Ah Ha!
Big up to Kobby for his contribution.
I think I figured out why I was having a problem...I was thinking of processing as if it were python. If this were python:
I remembered watching MIT's open courseware, and I remembered they used evens and odds in one of their examples, and here's what they did:
Copy code
  1. x = 15 
  2. if (x/2)*2 == x: print 'Even'
  3. else: print 'Odd'
That ^ wouldn't work in processing because it's necessary to declare whether x is an integer or float.

Again, massive thank you to Kobby for this one, you definitely saved me a lot of time!