【问题标题】:Different results when casting int and const int to float将 int 和 const int 转换为 float 时的不同结果
【发布时间】:2013-06-08 14:49:31
【问题描述】:

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

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) 被隐式转换为双精度值。 这是正确的,如果是这样,为什么会发生这种情况? 另外,什么是“正确”的方法?

非常感谢

【问题讨论】:

  • 在您的每个示例中, printf 的参数都被提升为 double。

标签: c casting floating-point int constants


【解决方案1】:

编译器可以在代码生成之前执行两个常量的乘法运算。其余的必须在运行时完成。

【讨论】:

  • 嗨,马克,谢谢您的回复。为什么编译器执行和运行时执行的乘法会给出不同的结果?
  • 我的猜测是编译器会以双精度执行所有浮点数学运算,即使最终结果是浮点数。
  • @LeeDanielCrocker:很可能反过来;编译器可能使用float 评估.3f * y,因为这正好产生300。通过将.3fy 转换为double 来评估.3f * y 会产生另一个值,接近300.0000119209。您可以通过将.3f 视为double 常量(完全忽略f,因此它根本不会转换为float)得到300,然后乘以1000,但这将是一个更大的缺陷编译器。然后在将.3f 转换为float 之后,使用double 或更高版本计算其他三个表达式。
猜你喜欢
  • 1970-01-01
  • 2019-06-24
  • 2015-05-30
  • 2020-12-14
  • 2016-11-11
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
相关资源
最近更新 更多