Suppose I want to divide two integer variables and put the result into a float. In order to prevent integer division do I have to program like this:

    int i = 6312;
    int j = 258;
    float f;
    f = i;
    f = i/j;

Or can I straightforward program like below and the compiler makes sure it is handled the 'proper' way:

    f = i/j;
  • 1
    why don't you run a test? – jsotola Jan 5 at 23:43

Cast the integers to float before doing the calculation.

float f = float(i) / float(j);


float f = (float) i / (float) j;

Always be clear how the calculation should be done, so the compiler will do what you want it to do.

  • 1
    or float f = (float) i / j; – Juraj Jan 6 at 6:39
  • @Juraj, that relies on the compiler to do a float calculation when a float and a int are involved. I prefer to make it clear for someone reading the code and for the compiler what is going on without having to think about it. – Jot Jan 6 at 9:12

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.