Reputation: 227
Here is the output I'm getting "1 student(s) passed: Infinity" when I should be getting 100% instead of Infinity. Any insight on this issue would be greatly appreciated!
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);
}
}
Upvotes: 1
Views: 452
Reputation: 8274
The reason you are getting Infinity
is because you are dividing by 0 with floats (numFails == 0). (If you hadn't cast your division to a float, you would have gotten:
Exception in thread "main" java.lang.ArithmeticException: / by zero
!)
What you need to do is divide by the total number of scores, not just the number of failing scores. Like so:
percentPassed = (float) numPass * 100 / (numPass + numFails);
Upvotes: 0
Reputation: 5900
You should divide numPass by numTotal, not numFails. Smth like this:
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);
}
}
Upvotes: 0
Reputation: 6792
You are using wronfg formula for getting the percentage
Instead of ,
percentPassed = (float) numPass * 100 / numFails;
it should be
percentPassed = (float) numPass * 100 / totalNumOfStudents;
Also, the issue as rightly pointed is divide by zero which results to infinity.
Upvotes: 0
Reputation: 200158
grade = 'Z';
} while (grade != 'Z');
You are executing exactly one iteration through your loop. If numFails
happens to remain zero after it, division by zero ensues.
Upvotes: 0
Reputation: 86411
If you want the percentage passed, you need to divide by the total, not the number failed.
float percentPassed = (((float) numPass) / (numPassed + numFailed)) * 100;
Upvotes: 1
Reputation: 53819
You are dividing a float
by zero, which gives infinity.
That is the case when numFails
is equal to 0
.
Upvotes: 0