c++ - 理解 double-to-int 转换中的 int-vs-trunc 关系

标签 c++ c++11 double codeblocks

当我运行以下代码时

#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/

相关文章:

java - 如何使用 Play 2.0 路由绑定(bind) Double 参数

c++ - 从在 postgresql 上运行的 C++ 文件打印

c++ - 在 CMake 项目中解耦应用程序和库

c++ - c++ 中深层嵌套函数的单个 catch all 语句?

c++ - operator==() 使用模板模板

c++ - 为什么我随机生成的数组只输出零?

c++ - 双倍与 float

c++ - 带有 std::is_reference 的 std::enable_if 编译失败

c++ - 为什么隐式和显式删除的 move 构造函数会受到不同对待?

swift - 获取超过 15 位小数的 Swift