Ok so I'm writing a program that gives a user a set of equations depending on how many they wish to do. After it runs and the user answers all the questions a report is generated. My code for the report is simple:
public void report(){
percent = (totalCorrect / numberOfQuestions) * 100;
totalTime = (endTime - startTime) / 1000;
System.out.println("Report:");
System.out.println("Questions Answered: " + numberOfQuestions);
System.out.println("Total Correct: " + totalCorrect);
System.out.println("Total Incorrect: " + totalIncorrect);
System.out.println("Percent: " + percent + "%");
System.out.println("Time taken: " + totalTime + " seconds");
}
However the result is:
Report:
Questions Answered: 2
Total Correct: 1
Total Incorrect: 1
Percent: 0.0%
Time taken: 2 seconds
This is correct, I purposely answered one correct and one incorrect. My question is the percentage is always 0.0% unless I get them all right in which case it is 100%. I don't understand what I'm doing wrong. It's recording the correct number of answers that are correct (based on the "Total Correct: " output) and the number of questions. And obviously my equation for percentage is correct. Any help would be much appreciated!
You most likely have performed integer division, if totalCorrect
and numberOfQuestions
are int
in your program. In integer division in Java, the result must also be an int
so the result is truncated.
Cast one of the variables to double
before performing the division, so Java will perform floating-point division first.
percent = ((double) totalCorrect / numberOfQuestions) * 100;
As others have pointed out, you're probably doing integer division.
One or both of your variables totalCorrect
and numberOfQuestions
needs to be a double, at least at the time of calculation.
Try this:
percent = ((double)totalCorrect / numberOfQuestions) * 100;
Maulzey gives another good alternative that doesn't cast from int to double.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.