在我的 while 循环中查找百分比工作不正常。嵌套while循环可以吗?

Finding the percentage in my while loop isn't working correctly. Is nested while loop ok?

我正在尝试学习 java while 循环。我正在尝试制作一个程序,该程序将计算一组学生的通过考试分数并输出输入的分数总数,分数高于 69 的通过考试的数量,并显示通过考试的百分比。

我 运行 遇到的问题是我似乎无法获得正确输出的百分比。它一直显示 0.0。以下是我迄今为止想出的最好的代码。

嵌套的 while 循环是好的编码风格吗?有没有更简单的方法来缩短我的程序?谢谢

    import java.util.Scanner;
    import java.text.DecimalFormat;

    public class CountPassingScores {

     public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        // Formats the percentage output to one decimal place.
        DecimalFormat df = new DecimalFormat("###,##0.0");

        // counts how many times a score is entered. Passing score is not
        // considered here.
        int count = 0;
        // The score the user enters.
        int score = 0;
        // percent of the class that passed the test. Passing score is 70 and
        // above.
        double percentOfClassPassed = 0.0;
        // total number of tests passed. Passing score is 70 and above.
        int numberOfTestsPassed = 0;

        System.out.println("This program counts the number of passing "
                + "test scores. (-1 to quit)\n");

        while (score != -1) {
            System.out.print("Enter the first test score:  ");
            score = scan.nextInt();

            while (count != -1 && score > 0) {
                System.out.print("Enter the next test score:  ");
                score = scan.nextInt();
                count++;

                if (count == -1)
                    break;
                else if (score > 69)
                    numberOfTestsPassed++;
                percentOfClassPassed = (numberOfTestsPassed / count);
            }

        }

        System.out.println("\nYou entered " + count + " scores.");
        System.out.println("The number of passing test scores is "
                + numberOfTestsPassed + ".");
        System.out.println(df.format(percentOfClassPassed)
                + "% of the class passed the test.");
    }
}

那是因为您将 intint 相除。这只会导致 int

要获得正确的结果,请将任何一个转换为 double

percentOfClassPassed = ((double) numberOfTestsPassed / count);

您的代码不会将 92 视为测试通过分数,因为您没有在第一个 while 循环中递增 numberOfTestsPassed 的值。以下是我对您的代码片段所做的一些更改:

    while (score != -1) {
        System.out.print("Enter the first test score:  ");
        score = scan.nextInt();
        if(score > 69)
        numberOfTestsPassed++;
        while (count != -1 && score > 0) {
            System.out.print("Enter the next test score:  ");
            score = scan.nextInt();
            count++;
            if (score == -1)
                break;
            else if (score > 69)
                numberOfTestsPassed++;
        }
         percentOfClassPassed = ((double)numberOfTestsPassed * 100 / count); 
    }

它为所有输入提供了正确的输出。