Java 如何查找数组元素的平均值
如何计算数组元素的平均值
创建一个程序来计算不同年龄的平均值
示例
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
float avg, sum = 0;
// Get the length of the array
int length = ages.length;
// Loop through the elements of the array
for (int age : ages) {
sum += age;
}
// Calculate the average by dividing the sum by the length
avg = sum / length;
// Print the average
System.out.println("The average age is: " + avg);