新手请教一个十分简单的问题

来源:百度知道 编辑:UC知道 时间:2024/05/07 08:29:05
我刚学JAVA不久 昨天在做一道联系题时碰到了问题
题目大概是叫我用for loop重复提示5个showInputDialog 让用户分别输入5个DOUBLE数字,并将这5个DOUBLE数字放入Array中, 以上几点我做到了,
但是下面题目又要求让我再用一次for loop判断出这5个储存在Array中的数字其中最大的数,最小的数,以及5个数总和的平均数, 请问下如何用for loop解决这个问题?感激不尽!

按照你的要求,只用了一次for loop
public class Test {
// 我直接写成static方法了,你把数组作为参数传进去就ok了
public static void printNumber(double[] arrays) {
double max = arrays[0];
double min = arrays[0];
double sum = arrays[0];
for (int i = 1; i < arrays.length; i++) {
double temp = arrays[i];
sum += temp;
if (max < temp) {
max = temp;
} else if (min > temp) {
min = temp;
}
}
// 最后把它们打印出来
System.out.println("the max number is : " + max + "\nthe min number is : "
+ min + "\nthe average is : " + sum / arrays.length);
}

public static void main(String[] args) {
// 下面用个简单的数组测试一下
double[] arrays = new double[] { -21.88, 0, 1.16, 1231,321.321};
Test.printNumber(arrays);
}
}

无敌小咪 你好:
楼上的仁兄 解释的很合理,我这里也不说废话了
想告诉你也可以来这个群里咨询讨论 :