4

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;
PimV
  • 443
  • 4
  • 12
  • 1
    why don't you run a test? – jsotola Jan 05 '19 at 23:43
  • 1
    Isn't there a typo in your first block of code? Did you mean to write f = f/j;? Otherwise, (a) why bother assigning f = i;? and (b) the last line of the first block is exactly the same as the line in the second block... So the question doesn't make much sense... unless you made a typo... – Greenonline Sep 08 '21 at 16:30
  • 2
    @Greenonline: you are correct, in the first block of code I should have written f = f/j; – PimV Sep 09 '21 at 10:00

2 Answers2

4

Cast the integers to float before doing the calculation.

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

or

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.

Jot
  • 3,246
  • 1
  • 13
  • 21
  • 3
    or float f = (float) i / j; – Juraj Jan 06 '19 at 06: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 06 '19 at 09:12
1

As Arduino is C++, you should really use a static cast, to be technically accurate. However, for Arduino code it probably doesn't really matter.

So either

float f = static_cast< float >(i) / static_cast< float >(j);

or

float f = static_cast< float >(i) / j;

Note: Using a static cast on each operand, rather than just one, is useful to quiet any warnings about the loss of precision with int to float, which typically needs to form a rounded float for large int values.

See C++ int float casting for more info.


Just to add to Jot's answer: Strictly speaking, it should be pointed out that (float) is C, whereas float() is C++.


Also, as you had meant to write in your question:

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

Yes, that would work. However, even though it seems quite elegant, it could cause confusion later in time, when someone else examines the code - unless you added a comment explaining why.

it is probably best to keep the code simple and obvious (for debugging purposes) unless you are deliberately intending to obfuscate the code.

Greenonline
  • 2,938
  • 7
  • 32
  • 48