Reputation: 1
I want to write a program to see if an integer is the power of another integer(true return 1 and false return 0). And the code is as follows:
#include <stdio.h>
#include <math.h>
int cal_base_power(int);
int main()
{
int x,r;
printf("Please input an integer\n");
scanf("%d\n",&x);
r=cal_base_power(x);
printf("result is %d\n",r);
}
int cal_base_power(int input)
{
int i=2;
double a=pow(input,(double)1/i);
while (a>=2)
{
if ((double)a==(int)a)
return 1;
i++;
a=pow(input,(double)1/i);
}
return 0;
}
It is ok with 4,8,125 some cases like these. But failed when input 216 and 343. Also it will not automatically output 0 and 1. I must input some random characteristics before the result 0 or 1 comes out. Can anyone help me? I know it is quite easy. But I really need your help
Upvotes: 0
Views: 90
Reputation: 471379
You can't do equality comparisons on floating-point.
(double)a==(int)a
Due to round-off error, a
might not be exactly an integer even though it's supposed to be.
EDIT:
There's two ways to do this:
fabs(a - (int)a) < 0.0001
(or something like that, you'll need to tweak the threshold.)a
to the nearest integer and power it back up (using integers only) to see if it matches the input.Upvotes: 4