不同的结果,当铸造int和const int的浮动 [英] Different results when casting int and const int to float

查看:91
本文介绍了不同的结果,当铸造int和const int的浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

会有人能够解释为什么int和const int的给予不同
投浮在浮点运算使用时,结果?请参阅
比如这块code的:

Would anyone be able to explain why int and const int give different results when cast to float and used in floating point math? See for example this piece of code:

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)被隐式转换为float,
而在第二种情况下,0.3f *(const int的)被隐式转换为双。
这是正确的,如果是这样,为什么会这样?
此外,什么是正确的方法呢?

My guess is that in the first case 0.3f*(int) is implicitly cast to a float, whereas in the second case 0.3f*(const int) is implicitly cast to a double. Is this correct, and if so why does this happen? Also, what is the "right" approach?

非常感谢

推荐答案

甚至产生code之前,由编译器执行两个常量的倍增。其余的必须在运行时完成。

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.

这篇关于不同的结果,当铸造int和const int的浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆