Something is wrong with my float operation

I have to miss something, what's wrong with that?

float controlFrameRate = 1/60; 

Something like 0.0166666667 should be assigned, but its appearance is 0.00000, etc. Is it a visual studio just lying to me?

+2
c ++ operators
source share
4 answers

This is because 1/60 is an integer that is 0, because integer division is truncated. This is used to initialize the float, providing 0. .. You can fix this by making the RHS float expression first:

 float controlFrameRate = 1.0f/60; 

about

 float controlFrameRate = 1/60.0f; 

In C ++, literals such as 1 , 42 , etc., int , 1.0 , 3.1416 are double , and f in 1.0f makes a literal a float . Note that f could be excluded in the examples above. However, assigning a double value to a float can be problematic if the double value is outside the range of the float.

+7
source share

Dividing an integer into another integer gives an integer and is a truncated operation. You will get a value that is less than or equal to the actual value.

Make at least one of the floating point constants to fix it:

 float controlFrameRate = 1.0 / 60; float controlFrameRate = 1 / 60.0; float controlFrameRate = 1.0 / 60.0; 
+3
source share

Do

  float controlFrameRate = 1.f/60; 

or

  float controlFrameRate = 1/60.f; 

or

  float controlFrameRate = 0.1f/6; 

; -)

+2
source share

You must use 1/60.0 . otherwise, you will not get a float result.

0
source share

All Articles