为什么我的变量设置为0?

Acr*_*ron 0 java parameters

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参数是不是?

Naw*_*Man 5

尝试:

// computes x^(1/n)
    public static double rootNofX(int n, double x) {
        return power(x, 1.0/n);
    }
Run Code Online (Sandbox Code Playgroud)

因为1intn是一个int如此1/n是一个整数除法,其返回0时n不为1,当n为0抛出错误.

1.0是一个双倍,所以它做1.0/n了你想要的双重划分.

  • 你还必须将方法`power`的参数`n`更改为`double`,否则它仍然无效. (2认同)