-2

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?

pop rock
  • 517
  • 1
  • 6
  • 14

2 Answers2

3

(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 ;
Clifford
  • 88,407
  • 13
  • 85
  • 165
2

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.

Clifford
  • 88,407
  • 13
  • 85
  • 165
yellowtail
  • 435
  • 3
  • 12