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

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

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

问题

以下是翻译好的部分:

  1. public class HelloWorld{
  2. public static void main(String []args){
  3. double [] nums = {10.5, 11.50,12.50,13.50,14.50};
  4. double result = 0;
  5. int i;
  6. for(i=0; i<nums.length;i++){
  7. result = result+nums[i];
  8. System.out.println("平均值为 "+ result/5);
  9. }
  10. }
  11. }

当前的代码输出如下:

  1. 平均值为 2.1
  2. 平均值为 4.4
  3. 平均值为 6.9
  4. 平均值为 9.6
  5. 平均值为 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.

  1. public class HelloWorld{
  2. public static void main(String []args){
  3. double [] nums = {10.5, 11.50,12.50,13.50,14.50};
  4. double result = 0;
  5. int i;
  6. for(i=0; i&lt;nums.length;i++){
  7. result = result+nums[i];
  8. System.out.println(&quot;Average is &quot;+ result/5);
  9. }
  10. }
  11. }

My current code is displaying following:

  1. Average is 2.1
  2. Average is 4.4
  3. Average is 6.9
  4. Average is 9.6
  5. Average is 12.5

答案1

得分: 1

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

  1. for(i=0; i<nums.length;i++){
  2. result = result+nums[i];
  3. }
  4. System.out.println("Average is "+ result/5); // 从循环体中移出
英文:

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

  1. for(i=0; i&lt;nums.length;i++){
  2. result = result+nums[i];
  3. }
  4. System.out.println(&quot;Average is &quot;+ result/5); // Moved out from the loop body

答案2

得分: 1

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

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

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

  1. for(i=0; i&lt;nums.length;i++)
  2. result = result+nums[i];
  3. 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:

确定