gpt4 book ai didi

c++ - 关于 C++ 中 double 和 int 之间转换的奇怪结果

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:27:42 25 4
gpt4 key购买 nike

我的问题:

尝试找出以下 C++ 片段的结果:

#include <iostream>

int main(int argc, char* argv[])
{
double a = 5.1;
int b = a * 100;
std::cout << b << std::endl;

double c = 6.1;
int d = c * 100;
std::cout << d << std::endl;
}

在 Windows 上,我用 VS2008 SP1 编译并运行上面的代码,得到:

509
610

在 Linux 上,我使用 g++ 编译并运行了相同的代码并得到:

509
609

代码有什么问题?

抱歉,我试图为该问题找出一个标题,因此我可以四处搜索。不过这个问题我说不上来,所以直接在这里提出来。

如有任何建议,我们将不胜感激。

最佳答案

double 不是精确类型,正如您通过应用 std::numeric_limits typetrait 可以看到的那样:

#include <limits>

static_assert(std::numeric_limits<double>::is_exact == false);

因此涉及 double 的计算只是近似值,您观察到的结果没有错。

您的代码没有问题。

关于c++ - 关于 C++ 中 double 和 int 之间转换的奇怪结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12353616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com