质疑Math.sqrt对方法的准确性

时间:2015-03-08 19:53:24

标签: java

我创建了一个运行数组的方法,在数组中添加数字,然后找到总数的平方根。但是当我在计算器上检查总计的平方根时,我得到了一个完全不同的答案,我很担心。

我在计算器上得到的答案是3.16227766017。 当我运行代码时,我得到的答案是2.4850206733870595

我是编码的初学者,但我想确保我的代码中没有出错。代码如下:

public static void main(String[] args) {

   double array1[] = {1,2,3,4};
   double total = 0;

   for(double x : array1){
       total += x;
       total = Math.sqrt(total);
   }

   System.out.println(total);

}

运行:

2.4850206733870595
BUILD SUCCESSFUL (total time: 2 seconds)

2 个答案:

答案 0 :(得分:3)

你希望在 for循环结束后计算平方根

for (double x : array1) {
    total += x;
}
total = Math.sqrt(total);

答案 1 :(得分:2)

你的错误是你正在改变总数并且每次在for循环中将它设置为平方根

   for(double x : array1){
       total += x;
       total = Math.sqrt(total);
   }

这显然是错误的。在循环完成时,只需一次

class root {
 public static void main(String[] args) {

   double array1[] = {1,2,3,4};
   double total = 0;

   for(double x : array1){
       total += x;

   }
   total = Math.sqrt(total);
   System.out.println(total);
} }

您将在打印时获得正确的结果

3.1622776601683795