int percent = (score/numberOfQuestions)*100;
progressText.setText(score+\"/\"+numberOfQuestions+\" \"+percent+\"%\");
returns 0% no matter what I
score/numberOfQuestions
will always provide a number between 0 and 1. You have two choices depending upon how accurate you need your computation. For most things, you can change the expression to (score * 100)/numberOfQUestions
. This will give you two digits of accuracy. A problem would occur if score * 100
overflowed an int. Given your variable names, I doubt this would happen in this case. The second possibility would be to convert the expression to double for the computation.
int percent=(int)(((double)score/numberOfQuestions)*100);
The problem is that divide two integers gives you the integer part of the result. So, (score/numberOfQuestions)
will be always 0.
What you should do is
int percent = (score * 100 / numberOfQuestions);
Then the *100
will be executed first, then the divide will give you correct result.
You need to cast on either of them: -
float percent = ((float)score/numberOfQuestions)*100;
Since, 5 / 10
is already 0.. Casting the final result to any type will give you 0 only, as in below code: -
float percent = ((float)(score/numberOfQuestions))*100;
This will also give you 0.0
. Since you are casting 0
to float. Doesn't matter..
You're using an int
(integer) to store that percentage. Try using float
or double
instead making score and number of questions float
or double
too (Thanks for teh comments, I totally skipped this...). If you have issues showing the value, I suggest you use DecimalFormat to format it.
Rather than using pure int
math to calculate and store the percentage, I suggest this other alternatives if you want to have decimals in your result.
Check your integer math. Your code won't work without casting for small values, so just move the operations around:
int percent = 100*score/numberOfQuestions;