该程序将使用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
Run Code Online (Sandbox Code Playgroud)
我的结果:
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.
Run Code Online (Sandbox Code Playgroud)
除了最后一次打印之外,这是正确的:' Please enter the next exam: 96'我尝试将IF语句放在' sum'行和之间TextIO.put 'Enter next exam',但隔离它.
谢谢,来自程序员世界中的网络花花公子陷阱.
pol*_*nts 12
你有一个所谓的一个一个错误,加上你不必要地卷积你的循环逻辑这一事实.
关于循环,我建议两件事:
for (int i = 1; i <= N; i++); 这是非典型的
for (int i = 0; i < N; i++); 它更典型Double Avg在Java中,变量名以小写开头.而且,Double是一个引用类型,原始的框double.只要有可能,你应该更喜欢double到Double
int和an 之间有什么区别Integer?int num = Integer.getInteger(“123”)扔NullPointerException?boolean?new Integer(i) == i在Java中?(是!!!)这是一种重写代码的方法,使代码更具可读性.我用过,java.util.Scanner因为我不认为TextIO是标准的,但本质保持不变.
import java.util.*;
public class ExamsFor4 {
public static void main(String[] arguments) {
Scanner sc = new Scanner(System.in);
final int NUM_EXAMS = 4;
int sum = 0;
for (int i = 0; i < NUM_EXAMS; i++) {
System.out.printf("Please enter the %s exam: ",
(i == 0) ? "first" : "next"
);
sum += sc.nextInt();
}
System.out.printf("Total is %d%n", sum);
System.out.printf("Average is %1.2f%n", ((double) sum) / NUM_EXAMS);
}
}
Run Code Online (Sandbox Code Playgroud)
示例会话如下:
Please enter the first exam: 4
Please enter the next exam: 5
Please enter the next exam: 7
Please enter the next exam: 9
Total is 25
Average is 6.25
Run Code Online (Sandbox Code Playgroud)
注意:
final去做吧
(360 / 24) / 60 = 0用Java
(double)需要在上面的代码中进行除法之前的转换,以便执行浮点除法.?:上面代码中的运算符,也称为条件运算符.| 归档时间: |
|
| 查看次数: |
1268 次 |
| 最近记录: |