如何操作数组.求平均值.初级Java [英] How to manipulate arrays. Find the average. Beginner Java
问题描述
我有一个家庭作业,我想知道是否有人可以帮助我,因为我是 Java 和编程的新手并且被困在一个问题上.问题是:
I have a homework assignment and I was wondering if anyone could help me as I am new to Java and programming and am stuck on a question. The question is:
第一种方法求整数数组元素的平均值:
The first method finds the average of the elements of an integer array:
public double average(int[] data)
即给定一个整数数组,数据,计算其元素的平均值,均返回平均值.例如,{1, 3, 2, 5, 8} 的平均值为 3.8.
That is, given an integer array, data, calculate the average of its elements are return the average value. For example, the average of {1, 3, 2, 5, 8} is 3.8.
这是我到目前为止所做的:
Here is what I have done so far:
public double average(int[] data) {
int sum = 0;
while(int i=0; i < data.length; i++)
sum = sum + data[i];
double average = sum / data.length;;
System.out.println("Average value of array element is " " + average);
}
在编译它时,我在 int i=0
部分收到一条错误消息,说.class expected".任何帮助,将不胜感激.
When compiling it I get an error message at the int i=0
part saying '.class expected'. Any help would be appreciated.
推荐答案
使用增强的 for 会更好:
Using an enhanced for would be even nicer:
int sum = 0;
for (int d : data) sum += d;
另一件可能会让你大吃一惊的事情是你将获得的错误结果
Another thing that will probably give you a big surprise is the wrong result that you will obtain from
double average = sum / data.length;
原因:右侧有整数除法,Java 不会自动将其提升为浮点除法.它将计算 sum/data.length
的整数商,然后才将该整数提升为 double
.一个解决方案是
Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length
and only then promote that integer to a double
. A solution would be
double average = 1.0d * sum / data.length;
这将强制被除数变成 double
,它会自动传播到除数.
This will force the dividend into a double
, which will automatically propagate to the divisor.
这篇关于如何操作数组.求平均值.初级Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!