用于循环结构

jja*_*n89 1 java

该程序将使用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.只要有可能,你应该更喜欢doubleDouble

也可以看看

相关问题


改写

这是一种重写代码的方法,使代码更具可读性.我用过,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去做吧
    • Java中的常量都是大写的

相关问题


归档时间:

查看次数:

1268 次

最近记录:

13 年,6 月 前