仍然掌握着java,直到现在我已经完成了任务,没有任何打嗝.当我计算我的数组内的值的平均值时,我得到一个不正确的答案.这是获取值的代码:
public static int [] inputGrades()
{
Scanner kb = new Scanner (System.in);
int [] iGrades = new int [10];
System.out.print("\nInput test scores, enter -1 when you're finished.\n");
for (int i =0; i<iGrades.length;i++)
{
iGrades[i]=kb.nextInt();
if (iGrades[i] ==-1)
{
break;
}
}
return iGrades;
Run Code Online (Sandbox Code Playgroud)
那么这是我的阵列的平均方法:
public static double averageArray (int [] array, int numElements)
{
int iSum= 0;
double dAverage;
for (int i=0; i<array.length; i++)
{
if (array[i]>0)
{
iSum = iSum + array[i];
}
}
dAverage = iSum / array.length;
System.out.print (dAverage);
return dAverage;
Run Code Online (Sandbox Code Playgroud)
如果我输入说10,20,30,40,50,-1.我得到的平均值的输出是15而不是30.任何想法为什么?谢谢.
有两个问题在起作用:
(1)这是整数(即截断)除法:
dAverage = iSum / array.length;
Run Code Online (Sandbox Code Playgroud)
你要
dAverage = iSum / (double)array.length`;
Run Code Online (Sandbox Code Playgroud)
(2)array.length总是10并且在数组的末尾包括零.因此,在您的示例中,您实际上计算的是10,20,30,40,50,0,0,0,0,0的平均值,实际上是15.
您需要记录用户实际输入的数量,并将其除以.
更好的是,使用一个ArrayList<Integer>而不是int[],你可以完全回避这个问题.
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |