我正在尝试学习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.");
}
}
答案 0 :(得分:1)
那是因为您要将int
与int
分开。这将导致仅int
。
要获得正确的结果,请将任何一个投放到double
。
percentOfClassPassed = ((double) numberOfTestsPassed / count);
答案 1 :(得分:1)
您的代码并未考虑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);
}
它为所有输入提供正确的输出。