浮点编译时计算不会发生? [英] Float compile-time calculation not happening?

查看:126
本文介绍了浮点编译时计算不会发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个小测试程序:

#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;
}

结果:

0
0.0166667

& 2010。

Tested on Visual Studio 2008 & 2010.


  1. 我在其他编译器上工作,如果我记得很好,第一个结果就像第二个结果。现在我的内存可能是错误的,但不应该TEST_FLOAT具有相同的值比TEST_C?如果不是,为什么?

  2. 在编译时或运行时解析TEST_C值?我总是假设前者,但现在我看到这些结果我有一些疑问...


推荐答案

p> 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

(您可以选择使用 1.0f ,以避免任何精确减少警告; 1.0 有类型 double ,而 1.0f 有类型 float

(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)


't TEST_FLOAT 的值与 TEST_C 相同?

TEST_FLOAT 情况下,执行整数除法,然后整数除法的结果转换为 float

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

TEST_C 案例中,整数文字 1 60 分配到 TEST_A float >和 TEST_B ;则对这些浮点执行浮点除法,并将结果分配给 TEST_C

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.


在编译时或运行时是否解析了 TEST_C 值?

它取决于编译器;任何一种方法都符合标准。

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

这篇关于浮点编译时计算不会发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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