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