Hi there,

I am writing a program that is taking a number and finding its cube roots and then prints out whether the result is an odd or an even number. I have written the following code but for some reasons it is not giving me the right answer. Could you please help me with this.

#include <cmath>
#include <stdio.h>

int main()

double NbSites=216;
double numofsites = pow(NbSites,1./3.);
printf ("\n %f", numofsites);
printf ("\n %f", fmod(numofsites,2));

if ( fmod(numofsites,2) == 0) printf(" Even Lattice \n");
else printf (" Odd Lattice \n");


Any suggestion is very much appreciated.

7 Years
Discussion Span
Last Post by SakuraPink

fmod(something) == 0 should be fmod(something) == 0.0 Otherwise a slight error might be because of limits of the representation of floating point numbers.

Edited by pseudorandom21: n/a


To see if a number is even you can just check the remainder when divided by 2 or check the last bit. For floating number, you can just check the integer part, so there is no need to use fmod since comparing it to 0.0 might not do what you expect everytime.

float f1 = 123.3243f;
cout << (int(f1) % 2 == 0 ? "even" : "odd" ) << endl;

Thanks a lot for your replies.
pseudorandom21 I tried that still the same answer.
to firstPerson thanks it worked :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.