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给出的值为2的rootNofX的参数吗?为什么我的变量设置为0?
您循环工作?你的例子是试图找到9的平方根。你是如何看待这个代码将循环1/2的时间和半乘1 * 9得到3的?你需要一个不同的算法来执行0和1之间的权力。 – jmucchiello 2009-11-08 01:54:05
FYI:x ^(1/2)!= 1 /(x^2) 请重新学习关于指数和对数的法则。 - Jakob Krainz,Lehrstuhl 2 Informatik,Univ。 Erlangen – jakob 2013-11-11 11:11:30