I am working with STM32 and GCC Compiler and I make the following division:
uint8_t w, h;
w=2;
h=5;
float test = (w * h) / 8;
and the result is test=1
Why am I wrong? I cannot understand this behavior.
Could someone explain me the reason?
(w * h) / 8
is an integer expression with an integer result.
The assignment to float
is an implicit cast, but will not recover the lost fractional part.
You can make the division a floating point expression by ensuring that at least one of the operands is floating point:
float test = (w * h) / 8.0f ;
You need to do the following modification if you want to get the correct result:
uint8_t w, h;
w = 2;
h = 5;
float test = (float)(w * h) / 8;
If you divide integers, you get an integer as a result.