JAVA – 寻找 double 类型数组的平均值 – 我的代码不起作用

huangapple go评论86阅读模式
英文:

JAVA - Finding the average value of a double type Array - my code doesn't work

问题

以下是翻译好的部分:

public class HelloWorld{

     public static void main(String []args){
        double [] nums = {10.5, 11.50,12.50,13.50,14.50};  
        double result = 0;
        int i;
        for(i=0; i<nums.length;i++){
            result = result+nums[i];
            System.out.println("平均值为 "+ result/5);
        }
  
     }

}

当前的代码输出如下:

平均值为 2.1
平均值为 4.4
平均值为 6.9
平均值为 9.6
平均值为 12.5
英文:

My code supposed to do following:

  1. Add up all the double values from this particular array: double nums[] = {10.5, 11.50,12.50,13.50,14.50}

  2. After that it should be divided by 5 or nums.length

All in all I should get 1 result, but my code is showing me nums[i]/5 for each element individually.

Please check my code and tell me, what I did wrong.

public class HelloWorld{

     public static void main(String []args){
        double [] nums = {10.5, 11.50,12.50,13.50,14.50};  
        double result = 0;
        int i;
        for(i=0; i&lt;nums.length;i++){
            result = result+nums[i];
            System.out.println(&quot;Average is &quot;+ result/5);
        }
  
     }

}

My current code is displaying following:

Average is 2.1
Average is 4.4
Average is 6.9
Average is 9.6
Average is 12.5

答案1

得分: 1

将打印行移出循环,以便平均值仅打印一次。

for(i=0; i<nums.length;i++){
    result = result+nums[i];        
}

System.out.println("Average is "+ result/5); // 从循环体中移出
英文:

Move the printing line out of the loop so that the average is printed only once.

for(i=0; i&lt;nums.length;i++){
    result = result+nums[i];        
}

System.out.println(&quot;Average is &quot;+ result/5); // Moved out from the loop body

答案2

得分: 1

你正在循环内部也打印了平均值。你想要做的是这样的:

for(i=0; i<nums.length; i++)
    result = result + nums[i];
System.out.println("平均值为:" + result / 5);
英文:

You are printing the average also inside the loop. What you would wanna do is something like this :

for(i=0; i&lt;nums.length;i++)
    result = result+nums[i];
System.out.println(&quot;Average is &quot;+ result/5); 

huangapple
  • 本文由 发表于 2020年10月21日 01:17:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64450246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定