java - 为什么我的变量设置为 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);
    }
}

每当调用 power(x,1/n) 时,n 都会重置为 0。但是 n 不是赋予 rootNofX 的参数,值为 2 吗?

最佳答案

尝试:

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

因为 1 是一个 intn 是一个 int 所以 1/n 是一个整数除法,当 n 不为 1 时返回 0,当 n 为 0 时抛出错误。

1.0 是一个 double ,因此它使 1.0/n 成为您想要的双除法。

关于java - 为什么我的变量设置为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1695038/

相关文章:

java - Java是如何实现链表的

java - 让 Jedis 与 JMeter 引擎一起工作

oop - 方法调用作为另一个方法调用的参数?

c - 如果我声明一个参数表为空的函数,然后将参数传递给它会怎样?

java - 如何在数据库访问中使用 Future

java - : I have a requirement of matching the value request parameter with unicode charcters but it should not allow space 的正则表达式

typescript 仅从重载中选择特定方法(要传递给 Parameters<T>)

c++ - 是否可以将函数参数存储为某种列表

function - 两个括号内自动缩进 - Vim

java - 为什么 Hadoop 无法在本地模式下找到这个文件,即使它存在?