Home > Blockchain >  Why is my power function not working properly here?
Why is my power function not working properly here?

Time:11-28

I've tried changing variable types but this is still not working.

double power(double a, long long b){

    while(b>1){
        a *= a;
        b--;
    }

return a;
}

CodePudding user response:

Your code won't run properly when b>2 because when you're doing a = a*a; the second time it won't be a^3 but a^4 and the next time it will be a^8 and so on. The right code would be something like this below:

double power(double a, long long b){

double k = 1;
    while(b>0){
        k *= a;
        b--;
    }

return k;
}

CodePudding user response:

You're changing a on every iteration. Say you call it like power(2, 3).

First you do 2 * 2 and assign this to a. Next iteration, you'll do again a * a which is 4 * 4. Just keep the result in a variable and don't change the arguments:

double power(double a, long long b){
    double r = a;
    while(b>1){
        r *= a;
        b--;
    }

    return r;
}
  • Related