Java – bad operand type of binary operator ‘^’
•
Java
Try to create a recursive method to promote a double value to the int permission of the java course The instruction says, "however, write code so that when n is an even number, the method will return (x ^ (n / 2)) ^ 2."
This is what I have done so far:
public static double powerFaster(double x,int n) {
if (n == 0) {
return 1;
}
else if ((n % 2) == 0) {
return ((x ^ (n / 2.0) ^ 2.0)); //Error occurs here.
} else {
return x * powerFaster(x,(n - 1));
}
}
Solution
^Is an XOR operator, not a power Using math Pow () to get power
In other words, I think you missed the point of the exercise
You should return powerfast (x, N / 2) * powerfast (x, N / 2); When n is even (actually a recursive call is made, the result is stored in a variable and multiplied by itself)
public static double powerFaster(double x,int n) {
if (n == 0) {
return 1;
}
else if ((n % 2) == 0) {
double pow = powerFaster(x,n/2);
return pow * pow;
} else {
return x * powerFaster(x,(n - 1));
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
