Doesn't floating point calculation?

A small test program:

#include <iostream> const float TEST_FLOAT = 1/60; const float TEST_A = 1; const float TEST_B = 60; const float TEST_C = TEST_A / TEST_B; int main() { std::cout << TEST_FLOAT << std::endl; std::cout << TEST_C << std::endl; std::cin.ignore(); return 0; } 

Result:

 0 0.0166667 

Tested on Visual Studio 2008 and 2010.

  • I worked on other compilers, which, if I remember well, made the first result, as the second result. Now my memory may be wrong, but shouldn't TEST_FLOAT have the same meaning as TEST_C? If not, why?
  • Is TEST_C allowed at compile time or at runtime? I always accepted the first, but now, when I see these results, I have some doubts ...
+1
source share
1 answer

IN

 1/60 

Both operands are integers, so integer arithmetic is performed. To perform floating point arithmetic, at least one of the operands must be a floating point type. For example, any of the following will perform floating point separation:

 1.0/60 1.0/60.0 1/60.0 

(Instead, you can use 1.0f to avoid warnings about reduced accuracy; 1.0 is of type double , and 1.0f is of type float )

Shouldn't TEST_FLOAT have the same meaning as TEST_C ?

In the case of TEST_FLOAT , integer division is performed, and then the result of integer division is converted to float in assignment.

In the case of TEST_C integer literals 1 and 60 converted to float when they are assigned TEST_A and TEST_B ; then floating-point division is performed on these floats, and the result is assigned to TEST_C .

TEST_C allowed at compile time or at runtime?

It depends on the compiler; any method will meet the standards.

+11
source

Source: https://habr.com/ru/post/1315203/


All Articles