C is defined to divide `int`

s using integer division, and only when there is a float does it “promote” other `int`

s to `float`

s first. Note that this even happens if it will be assigned to a `float`

– if the right-hand side is all `int`

s, 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 `int`

s, 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);`

## Related Posts via Categories

### Comments

comments