英文:
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:
-
Add up all the double values from this particular array: double
nums[] = {10.5, 11.50,12.50,13.50,14.50}
-
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<nums.length;i++){
result = result+nums[i];
System.out.println("Average is "+ 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<nums.length;i++){
result = result+nums[i];
}
System.out.println("Average is "+ 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<nums.length;i++)
result = result+nums[i];
System.out.println("Average is "+ result/5);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论