I have a simple code, part of which contains the calculation 800/1000, which seems to return a value of zero for some reason (even though I store it in a float variable). When I replace the calculation with the expected result (0.8) the code works as expected, I just wonder why the calculation doesn't produce the same result.

  • The expression is first evaluated as an int, hence 0, before converting it to float. If you want the expression computed as a float, then at least one argument must be a flost, e.g. 800.0 / 1000. – jfpoilpret Jun 19 '15 at 4:33

Both 800.0/1000 or ((float)800)/1000 will work.

The former works only with hardcoded constants, while the latter works also with variables:

int a = 800;
int b = 1000;
float c = ((float)a) / b;

A whole numbers like 800 or 1000 are integers, while a number like 800.4 is considered fractional and is treated as a float. Two integers divided gives an whole integer result, in your case 0. If one number in the division is an integer, and one is a float, the result is a float.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.