【发布时间】:2024-01-19 07:48:01
【问题描述】:
我正在为我的大学课程研究一个数组问题,我正在尝试找到一个数组的总和和平均值。这是我到目前为止的代码。
public class Module55
{
public static void main(String args[])
{
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = new int[10];
int sum = 0;
double average = 0;
//declare the array values
weeks[0]= 2;
weeks[1]= 4;
weeks[2]= 8;
weeks[3]= 10;
weeks[4]= 14;
weeks[5]= 16;
weeks[6]= 20;
weeks[7]= 22;
weeks[8]= 24;
weeks[9]= 26;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++) weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
我知道平均值有效,但我坚持总和。我遇到的问题是我似乎无法初始化数组中的值,以便为它们提供总和。我做错了什么或者我错过了什么?
【问题讨论】:
-
也许您想删除循环语句
weeks[index] = index;?这根本没有意义。此外,下一行sum = sum + weeks[index];似乎是循环语句。 -
您的 for 循环中只有一条语句:
weeks[index] = index; -
刚刚更新了我的答案,也解决了你的精度问题,你可以去看看。