gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:31:30 25 4
gpt4 key购买 nike

我正在尝试学习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.");
}
}

最佳答案

您的代码不会将 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);
}

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

关于java - 在我的 while 循环中查找百分比无法正常工作。嵌套while循环可以吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31398382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com