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 x, 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);
}
}
每当调用 power(x,1/n) 时,n 都会重置为 0。但是 n 不是赋予 rootNofX 的参数,值为 2 吗?
最佳答案
尝试:
// computes x^(1/n)
public static double rootNofX(int n, double x) {
return power(x, 1.0/n);
}
因为 1
是一个 int
而 n
是一个 int
所以 1/n
是一个整数除法,当 n 不为 1 时返回 0,当 n 为 0 时抛出错误。
1.0
是一个 double ,因此它使 1.0/n
成为您想要的双除法。
关于java - 为什么我的变量设置为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1695038/