Skip to main content
NNam.18
Associate II
December 1, 2019
Solved

Why float X = 3300/2000 = 1?

  • December 1, 2019
  • 3 replies
  • 1384 views

I have a simple calculate

#define VREF ((uint16_t) 3300)
 
float X = VREF / 2000;

Why X result is 1? This happen with another calculate like xx00 / xx000

Thanks

This topic has been closed for replies.
Best answer by Piranha

The first line is useless in this example... The numbers 3300 and 2000 on the second line are interpreted as integers and division is done on integers, which gives the result = 1. If you add ".0", they will be interpreted as double type values, and, if you add ".0f", then as a float type values. That is for constant values, but, if you need to divide integer variables and get float type result, then cast the variables to float type before division.

https://stackoverflow.com/questions/5026570/suffix-of-f-on-float-value

P.S. This is one of the topics, which almost no one cares to explain in their tutorials, university courses etc.

3 replies

Piranha
PiranhaAnswer
Principal III
December 1, 2019

The first line is useless in this example... The numbers 3300 and 2000 on the second line are interpreted as integers and division is done on integers, which gives the result = 1. If you add ".0", they will be interpreted as double type values, and, if you add ".0f", then as a float type values. That is for constant values, but, if you need to divide integer variables and get float type result, then cast the variables to float type before division.

https://stackoverflow.com/questions/5026570/suffix-of-f-on-float-value

P.S. This is one of the topics, which almost no one cares to explain in their tutorials, university courses etc.

NNam.18
NNam.18Author
Associate II
December 1, 2019

sorry, I mean

#define VREF ((uint16_t) 3300)
 
float X = VREF / 2000;

Clive1 (HNL)
Explorer
December 1, 2019

float X = 3300.0f / 2000.0f;

S.Ma
Principal
December 1, 2019

Remember to avoid using float in interrupts routines. more registers to push/pop.