Why is my Variable set to 0?
import java.lang.Math;
public class NewtonIteration {
public static void main(String[] args) {
System.out.print(rootNofX(2,9));
}
// computes x^n
public static double power(double 开发者_如何学Pythonx, int n) {
if (n==0) {
return 1;
}
double Ergebnis = 1;
for (int i=0; i<=Math.abs(n)-1; i++) {
Ergebnis *= x;
}
if (n<0) {
Ergebnis = 1/Ergebnis;
}
return Ergebnis;
}
// computes x^(1/n)
public static double rootNofX(int n, double x) {
return power(x, 1/n);
}
}
Whenever power(x,1/n) is called, n is reset to 0. But isn't n a parameter given to rootNofX with the value 2?
Try:
// computes x^(1/n)
public static double rootNofX(int n, double x) {
return power(x, 1.0/n);
}
Because 1
is an int
and n
is an int
so 1/n
is an integer division which return 0 when n is not 1 and throw error when n is 0.
1.0
is a double so it make 1.0/n
a double division that you want.
1/n is going to be a fraction, usually, but in the declaration of power you declare n to be integer. That's going to knock off the decimal places every time!
It's because power is defined with "n" as an int so 1/n will always be less than 1 which will be zero when stored as an int. Update "int n" to "double n". Example below:
public static double power(double x, double n) { ... }
It's because you're using integers, so 1 / 2 = 0.5 which as an integer is 0. Change the prototypes to rootNofx(double n, double x)
and power(double x, double n)
.
Also, since rootNofx
uses power
, in my opinion, it would be better to have the parameters ordered the same way, to avoid confusion.
The problem is that you are passing 1/2 from rootNofX into an int, so it becomes zero.
There is a big difference between 1/n
and 1.0/n
Consider what declaring n
to be an int
really means...
精彩评论