How to Dividing with/without using floats in C

Published on Author Code Father

C is defined to divide ints using integer division, and only when there is a float does it “promote” other ints to floats first. Note that this even happens if it will be assigned to a float – if the right-hand side is all ints, then the division will all be integer, and only for the final assignment will C convert the int result to float.

So, with your line:

freq = LAB_Fmin + (((LAB_Fmax) - (LAB_Fmin))/ 255)*x ;

it all depends on what LAB_Fmax and LAB_Fmin are. It doesn’t matter what freq or x are, because the “damage” will already have been done due to the parentheses forcing the division to be first.

If those LAB_F variables are ints, the easiest way to use floating point division is to simply tell C that you want that by making the constant 255 a floating point number rather than an integer, by using a decimal point: 255. (or 255.0 to be less subtle).

If you want to use integer arithmetic only, then the usual suggestion is to do all of your multiplications before any divisions. Of course, this runs the risk of overflowing the intermediate result – to help that, you can use the type long. Define your LAB_F or x variables as long, and do the division last:

freq = LAB_Fmin + (((LAB_Fmax) - (LAB_Fmin)) * x / 255);

Comments

comments