【发布时间】:2010-07-11 15:55:04
【问题描述】:
该程序将通过提示使用 for 循环计算 4 门考试的平均成绩 考试成绩的用户,一次一个,然后计算平均值并显示结果。
public class ExamsFor4 {
public static void main(String[] arguments) {
int inputNumber; // One of the exams input by the user.
int sum = 0; // The sum of the exams.
int i; // Number of exams.
Double Avg; // The average of the exams.
TextIO.put("Please enter the first exam: "); // get the first exam.
inputNumber = TextIO.getlnInt();
for ( i = 1; i <= 4; i++ ) {
sum += inputNumber; // Add inputNumber to running sum.
TextIO.put("Please enter the next exam: "); // get the next exam.
inputNumber = TextIO.getlnInt();
if (i == 4) {
Avg = ((double)sum) / i;
TextIO.putln();
TextIO.putln("The total sum for all " + i +" exams is " + sum);
TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
break;
}
}
} // end main ()
} // end class ExamsFor4
我的结果:
Please enter the first exam: 100
Please enter the next exam: 99
Please enter the next exam: 98
Please enter the next exam: 97
Please enter the next exam: 96
The total sum for all 4 exams is 394
The average for the exams entered is 98.50.
这将是正确的,除了最后一个打印输出:'Please enter the next exam: 96'
我尝试将 IF 语句放在“sum”行和TextIO.put 'Enter next exam' 之间,但这会将其隔离。
感谢,来自程序员世界中的网络老兄陷阱。
【问题讨论】:
-
这是你应该努力解决的事情类型,要么自己解决,要么失败。我很高兴我在学校时没有将堆栈溢出作为资源。
标签: java