Simple question about my first C program: why isn't if(5.00000 == 5) coming as true?

Discuss Simple question about my first C program: why isn't if(5.00000 == 5) coming as true? in the C/C++ Help forum on Dev Articles. Simple question about my first C program: why isn't if(5.00000 == 5) coming as true? C/C++ Help forum discussing building and maintaining applications in C/C++. Find out why these languages are the foundation on which other languages are built.

Posts: 1
Time spent in forums: 45 m 48 sec
Reputation Power: 0

Simple question about my first C program: why isn't if(5.00000 == 5) coming as true?

I need to do the following:

take an int n, and an int m, and calculate the mth root of n (which I can do in C as pow(n,(double)1/m)

I then need to find out if the result is an integer.

I found that a suitable way in C to do this is:

double k = pow(n,(double)1/m);

int truncated = (int)k;
if( truncated == k ) { // the result was an integer; }

This seemed to work for awhile. It worked for example, when n = 16, and m = 2, in that case I got:

16^(0.5) = 4.00000
I then got truncated = 4, and the if statement was true.

However, as the number n got larger I noticed it isn't working. Best example being n = 3125 and m = 5. In this case I get: 3125^(1/5) = 5.0000000. But then for some reason the if statement fails.

I was curious why this happens?

EDIT:

Here is sample code you can use to test this out:

#include <stdio.h>
#include <math.h>

int main() {
double k = 0;
int truncated = 0;

// works on a small number
k = pow(16,(double)1/2);
truncated = (int)k;
printf("16 to the one half power is %f\n",k);
if( truncated == k ) {
printf("\tThis produced an integer\n");
}

// doesn't work on a larger number
k = pow(3125,(double)1/5);
truncated = (int)k;
printf("3125 to the one fifth power is %f\n",k);
if( truncated == k ) {
printf("\tThis produced an integer");
}

return 0;
}

This produces the output:

16 to the one half power is 4.000000
This produced an integer
3125 to the one fifth power is 5.000000

Furthermore, is there a better way also of testing if something is an integer?