Float compile-time calculation not happening?

五迷三道 提交于 2019-12-02 10:46:42

问题


A little 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 & 2010.

  1. I worked on other compilers that, if I remember well, made the first result like the second result. Now my memory could be wrong, but shouldn't TEST_FLOAT have the same value than TEST_C? If not, why?
  2. Is TEST_C value resolved at compile time or at runtime? I always assumed the former but now that I see those results I have some doubts...

回答1:


In

1/60

Both of the operands are integers, so integer arithmetic is performed. To perform floating point arithmetic, at least one of the operands needs to have a floating point type. For example, any of the following would perform floating point division:

1.0/60
1.0/60.0
1/60.0

(You might choose to use 1.0f instead, to avoid any precision reduction warnings; 1.0 has type double, while 1.0f has type float)

Shouldn't TEST_FLOAT have the same value than TEST_C?

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

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

Is TEST_C value resolved at compile time or at runtime?

It depends on the compiler; either method would be standards-conforming.



来源:https://stackoverflow.com/questions/2986324/float-compile-time-calculation-not-happening

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!