问题:统计信息通常是使用不同数量的输入数据来计算的。编写一个程序,将任意数量的非负整数作为输入,并输出平均值和最大值。负整数将结束输入,并且不包括在统计信息中。
Ex:当输入为: 15 20 0 5 -1
输出为: 10 20
您可以假定至少输入了一个非负整数。
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int num = 0;
int count = 0;
int max = 0;
int total = 0;
int avg = 0;
do {
total += num;
num = scnr.nextInt();
count = ++count;
if (num >= max) {
max = num;
}
} while (num >= 0);
avg = total/(count-1);
System.out.println(avg + " " + max);
}
}
我在这个问题上遇到很多麻烦。我有什么办法可以在计算平均值时不必做-1计数呢? 另外,这是我本可以做到的最有效的方法吗?
答案 0 :(得分:0)
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner (System.in);
int userNum;
int maxNum = 0;
int totalSum = 0;
int averageNum;
int count = 0;
userNum = scnr.nextInt();
while (userNum >= 0) {
if (userNum > maxNum) {
maxNum = userNum;
}
totalSum += userNum;
++count;
userNum = scnr.nextInt();
}
averageNum = totalSum / count;
System.out.println("" + averageNum + " " + maxNum);
}
}
答案 1 :(得分:0)
int Num;
int max = 0;
int total = 0;
int average;
int count = 0;
Num = scnr.nextInt();
while (Num >= 0) {
if (Num > max) {
max = Num;
}
total += Num;
++count;
Num = scnr.nextInt();
}
average = total / count;
System.out.println("" + average + " " + max);
}
}
答案 2 :(得分:-1)
这个怎么样?如果您对实施有疑问,请询问。
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
int num = scnr.nextInt();
while (num >= 0) {
count++;
total += num;
max = Math.max(max, num);
num = scnr.nextInt();
}
int avg = count == 0 ? 0 : total/count;
System.out.println(avg + " " + max);
}
如果使用while循环而不是do-while循环,则不必再计算输入的负数。不,这不是最有效的方法,但这是一个好的开始!