【发布时间】:2009-11-08 01:29:28
【问题描述】:
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 吗?
【问题讨论】:
-
在将 1/n 舍入为 0 后,您希望循环如何工作?您的示例试图找到 9 的平方根。您认为这段代码如何循环 1/2 次并半乘 1 * 9 得到 3?您将需要一种不同的算法来执行 0 到 1 之间的幂。
-
仅供参考:x^(1/2) != 1/(x^2) 请重新学习关于幂和对数的定律。 -- Jakob Krainz,Lehrstuhl 2 Informatik,大学。埃尔兰根
标签: java parameters