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<math.h>
#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.

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.

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 :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.