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);
}
}
Run Code Online (Sandbox Code Playgroud)
无论何时调用power(x,1/n),n都会重置为0.但是,对于rootNofX赋值为2的na参数是不是?
尝试:
// computes x^(1/n)
public static double rootNofX(int n, double x) {
return power(x, 1.0/n);
}Run Code Online (Sandbox Code Playgroud)
因为1是int和n是一个int如此1/n是一个整数除法,其返回0时n不为1,当n为0抛出错误.
1.0是一个双倍,所以它做1.0/n了你想要的双重划分.
| 归档时间: |
|
| 查看次数: |
273 次 |
| 最近记录: |