0

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

CUcainiao
  • 1
  • 1
  • This thread should be helpful http://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer – Mahesh Sep 13 '11 at 04:15
  • Are you sure you didn't mean to start `a` off as `sqrt(input)`? I mean, that's what you're doing, but the code you wrote is more complex. Nothing looks actually wrong with the code, though. Passes my check. – Borealid Sep 13 '11 at 04:15
  • `(double)a==(int)a` this is weird, because of the limited (huge but still limited) precision of floating point numbers, if I were you, I would try another solution... for instance start with 2, calculates its pows while < a, continue with 3 etc. – Simon Sep 13 '11 at 04:18
  • Mahesh, Borealid: he seems not looking for the sqrt of the number, but calculate if a number is a pow of any other number – Simon Sep 13 '11 at 04:21
  • Try an all-integer solution. You will need to turn the algorithm around, calculating the power rather than taking the roots, but it would be exakt (unlike a floating-point solution), it would be much faster, and (for a non-mathematician) you might have a chance to read and understand the code... – Lindydancer Sep 13 '11 at 05:10

1 Answers1

4

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:

  1. Allow tolerance on the comparison: fabs(a - (int)a) < 0.0001 (or something like that, you'll need to tweak the threshold.)
  2. Round a to the nearest integer and power it back up (using integers only) to see if it matches the input.
Mysticial
  • 464,885
  • 45
  • 335
  • 332