The problem is that the expression on the right-hand side is evaluated using integer arithmetic, and then casted to float when the assignment is done.
The easiest way to fix it is to have the first operand of the right-hand side be a float, so that the whole expression is evaluated using floating point arithmethic:
1 2 3
int a = ...;
int b = ...;
float percent = 100.0f * a / b;
Edit: I withdraw this recommendation. Don't do this. ;-)
Just two cents from me: It is absolutely not necessary to write the ".0f " on every place. The compiler will transform constants without any performance loss in the program.
So if it makes the code more readable, this is completely ok:
1 2
constfloat short_PI = 3.1415; // no "f" ending. Doesn't matter.
clearColor(0,0,0,0); // even if function takes float as parameter, this' work the same
Ciao, Imi.
PS: Just had to say this, as I think all those surplus .0f make code more unreadable sometimes. ;-)
Ok, you convinced me. Thinking twice about it.. I take back my former advice about the ".0f" and replace it with:
In case of doubt, add ".0f" (or ".f" if you're lazy and used to C) when you want a float. Only if you are really sure it won't cause harm, you can consider skip the ".0f". But it's safer and more consistent to just put it there anyway and it's quite easy for things to go wrong..
1 2 3 4 5 6 7 8
void clearColor(float r, float g, float b, float alpha) {...} // classic function taking argument from 0-1
// a coder came up with the idea of overloading for the common 0-255 case
void clearColor(int r, int g, int b, int alpha) { clearColor(r/255.f, g/255.f, b/255.f, alpha/255.f); }
...
// looks pretty. But is just wrong now.
clearColor(1,1,1,1); // supposed to set to opaque white.
Edit:
Technically, for a Floating literal (double) all you need to do is put a '.' after the digit sequence e.g. 255. therefor floats can just be '.F' e.g. 255.F
To make sure it is clear: 100 is an int 100.0 and 100. are double 100.0F and 100.F are float 100.0L and 100.L are long double