获得无限时应获得百分比

时间:2014-02-27 14:49:31

标签: java math

这是我得到的输出 “1名学生通过:无限” 当我应该得到100%而不是无限。对此问题的任何见解将不胜感激!

public class PassFailCount {
    public static void main(String[] args) {
        char grade;
        int numFails = 0;
        int numPass = 0;
        float percentFailed;
        float percentPassed;

        do {

            System.out.print("Enter a grade: ");
            grade = 'A';

            if (grade == 'A' || grade == 'B' || grade == 'C' || grade == 'D') {
                numPass++;
            } else {
                numFails++;
            }
            grade = 'Z';

        } while (grade != 'Z');

        percentPassed = (float) numPass * 100 / numFails;
        System.out.println(numPass + " student(s) passed: " + percentPassed);
    }
}

7 个答案:

答案 0 :(得分:1)

如果您希望通过百分比,则需要除以总数,而不是数字失败。

float percentPassed = (((float) numPass) / (numPassed + numFailed)) * 100;

答案 1 :(得分:1)

percentPassed = (float) numPass * 100 / (numPass+numFails);

答案 2 :(得分:0)

您将float除以0,得到无穷大。

numFails等于0时就是这种情况。

答案 3 :(得分:0)

       grade = 'Z';

    } while (grade != 'Z');

您正在循环执行一次迭代。如果numFails恰好在它之后保持为零,则接着除以零。

答案 4 :(得分:0)

您正在使用wronfg公式获取百分比

而不是,

 percentPassed = (float) numPass * 100 / numFails;

应该是

 percentPassed = (float) numPass * 100 / totalNumOfStudents;

此外,正确指出的问题是除以零,这导致无穷大。

答案 5 :(得分:0)

你应该将numPass除以numTotal,而不是numFails。像这样的Smth:

public class PassFailCount {
public static void main(String[] args) {
    char grade;
    int numTotal = 0;
    int numPass = 0;
    float percentFailed;
    float percentPassed;

    do {

        System.out.print("Enter a grade: ");
        grade = 'A';

        if (grade == 'A' || grade == 'B' || grade == 'C' || grade == 'D') {
            numPass++;
        }
        numTotal++;
        grade = 'Z';

    } while (grade != 'Z');

    if (numTotal != 0) {
        percentPassed = (float) numPass * 100 / numTotal;
    }
    System.out.println(numPass + " student(s) passed: " + percentPassed);
}

}

答案 6 :(得分:0)

您获得Infinity 的原因是因为您使用浮点数除以0(numFails == 0)。 (如果你没有把你的师加入浮动,你会得到:
Exception in thread "main" java.lang.ArithmeticException: / by zero!)

您需要做什么除以分数,而不仅仅是失败分数。像这样:

percentPassed = (float) numPass * 100 / (numPass + numFails);