Reputation: 21
I have been asked to calculate the result of x to the power of n using a while loop in java. This is my code:
public static double power(double x, int n){
int i = 1;
double y = 1.0;
while(i<=n){
i = i+1;
y = y*x;
return y;
}
return y;
}
It is not working because it just returns the original x. I can't figure out what is wrong x_x
Upvotes: 0
Views: 6582
Reputation: 394126
You are returning y after the first multiplication, which causes the value 1*x to be returned.
Don't return y inside the loop. Only return it after the loop is done.
while(i<=n){
i = i+1;
y = y*x;
return y; // remove this line
}
return y;
Upvotes: 1