I want to get two ints, one divided by the other to get a decimal or percentage.
How can I get a percentage or decimal of these two ints?
(I’m not sure if it is right.. I’m probably way off…)
for example:
int correct = 25;
int questionNum = 100;
float percent = correct/questionNum *100;
This is how I thought I could do it, but it didn’t work… I want to make the decimal (if there is one) into a percent out of 100 for example in this case it is %25. any ideas anyone?
Here is the correct code (thanks to Salvatore Previti!):
float correct = 25;
float questionNum = 100;
float percent = (correct * 100.0f) / questionNum;
(btw, I am making a project using this for a quiz checking program that is why I need the percentage or decimal)
If you don’t add
.0fit will be treated like it is an integer, and an integer division is a lot different from a floating point division indeed 🙂If you need an integer out of this you can of course cast the
floator thedoubleagain in integer.If you know your n value is less than 21474836 (that is (2 ^ 31 / 100)), you can do all using integer operations.
If you get NaN is because wathever you do you cannot divide for zero of course… it doesn’t make sense.