3

谁能解释为什么 int 和 const int 在转换为 float 并用于浮点数学时会给出不同的结果?参见例如这段代码:

int _tmain(int argc, _TCHAR* argv[])
{
      int x = 1000;
      const int y = 1000;
      float fx = (float) x;
      float fy = (float) y;

      printf("(int = 1000) * 0.3f = %4.10f \n", 0.3f*x); 
      printf("(const int = 1000) * 0.3f = %4.10f \n", 0.3f*y);
      printf("(float)(int = 1000) * 0.3f = %4.10f \n", 0.3f*fx); 
      printf("(float)(const int = 1000) * 0.3f = %4.10f \n", 0.3f*fy);
      return 0;
}

结果是:

(int = 1000) * 0.3f = 300.0000119209
(const int = 1000) * 0.3f = 300.0000000000
(float)(int = 1000) * 0.3f = 300.0000119209
(float)(const int = 1000) * 0.3f = 300.0000119209

我的猜测是,在第一种情况下 0.3f*(int) 被隐式转换为浮点数,而在第二种情况下 0.3f*(const int) 被隐式转换为双精度值。这是正确的,如果是这样,为什么会发生这种情况?另外,什么是“正确”的方法?

非常感谢

4

1 回答 1

2

The multiplication of two constants can be performed by the compiler before the code is even generated. The rest must be done at run-time.

于 2013-06-12T13:24:44.343 回答