cancel
Showing results for 
Search instead for 
Did you mean: 

Why float X = 3300/2000 = 1?

NNam.18
Associate II

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

1 ACCEPTED SOLUTION

Accepted Solutions
Piranha
Chief II

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.

View solution in original post

4 REPLIES 4
Piranha
Chief II

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.

Clive1 (HNL)
Senior II

float X = 3300.0f / 2000.0f;

sorry, I mean

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

S.Ma
Principal

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