【问题标题】:Error when running Custom Square Root Function (Java)运行自定义平方根函数 (Java) 时出错
【发布时间】:2016-08-08 05:28:00
【问题描述】:

所以我创建了一个方法来计算任何给定整数的平方根。对于像 27 这样的 x,我希望它显示 3√3。或者对于 28、2√7 等等。我会提前告诉你,我知道这种方法还有其他问题——我打算解决这些问题。

public static void root(int x) {
    int [] a = new int [x]; //list of outside integers for each i
    int b = x; //inside
    int c = 1; //product of a[]
    double sqrt = Math.sqrt(x);

    if (sqrt != (int) sqrt) {
        for (int i=2; i < x; i++) {
        a[i] = 1;
        while (x%(i^2) ==0) { //ERROR HERE
            a[i] = a[i] * i;
            b = b/(a[i])^2;
        }
        c = c * a[i];
        }
        System.out.println(b+"\u221A" + c);
    }
    else {
        System.out.println((int) sqrt);
    }
}

在执行任何不产生干净根的整数后,我收到一条错误消息“/零”。上面我标记了据说发生错误的地方。提前致谢!

【问题讨论】:

  • 您希望i^2 做什么

标签: java methods runtime-error square-root


【解决方案1】:

问题是这个表达式

x%(i^2)

运算符^ 不是求幂,它是按位异或。在第一次迭代中,i22 ^ 2 的结果是零。您试图除以零(以获得余数),但失败了。使用

x%(i*i)

改为。

【讨论】:

    【解决方案2】:

    在整个回答过程中,您使用^ 来计算平方数。然而,这实际上是一个按位异或运算符。相反,使用Math.pow(numToSquare, 2) 函数,或者简单地将数字或表达式乘以自身。

    【讨论】:

      猜你喜欢
      • 2022-06-13
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2021-07-02
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      相关资源
      最近更新 更多