当我运行以下代码时
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
enum { FACTOR = 3 };
double d = 1.0 / FACTOR;
double d_i = int(d * FACTOR);
int i_t = std::trunc(d * FACTOR);
double d_r = std::round(d * FACTOR);
cout << d_i << " vs " << i_t << " vs " << d_r << endl;
return 0;
}
在 Code::Blocks 17.12 IDE 中(使用我认为/希望的全包工具),我得到了这些令人困惑的结果:
0 vs 1 vs 1
我尝试更改编译器,但没有任何改变。最后我安装了 MinGW-64 版本 8.1.0。
我的构建日志显示
-------------- Clean: Debug in truncint (compiler: MinGW-w64-32bit)---------------
Cleaned "truncint - Debug"
-------------- Build: Debug in truncint (compiler: MinGW-w64-32bit)---------------
g++.exe -Wall -fexceptions -std=c++11 -g -std=c++11 -c C:\Users\[...]\truncint\main.cpp -o obj\Debug\main.o
g++.exe -o bin\Debug\truncint.exe obj\Debug\main.o
Output file is bin\Debug\truncint.exe with size 65.53 KB
Process terminated with status 0 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))
但奇怪的结果仍然存在。这可能是什么原因造成的?
遗憾的是,这似乎无法通过在线编译器进行重构。
最佳答案
事实证明,奇怪的结果仅限于调试 构建。
如果我切换到 Release,输出与 VS 2019 和我测试的所有在线编译器相同:
1 vs 1 vs 1
我不确定这是否可以作为答案,但更改构建目标解决了我的实际问题。
关于c++ - 理解 double-to-int 转换中的 int-vs-trunc 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57974462/