gpt4 book ai didi

c++ - C++ exp()函数确实有些奇怪

转载 作者:行者123 更新时间:2023-12-01 13:34:07 33 4
gpt4 key购买 nike

当试图在C++中实现 mySqrt 函数时,我使用了exp()函数,如下所示:

int mySqrt(int x) {
// For x = 2147395600
cout << exp(0.5*log(x)) << " "; // It prints 46340
return exp(0.5*log(x)); // But returns 46339
}

我试图用Google搜索这种行为的原因,但找不到任何东西。我什至尝试使用double,但输出仍然相同。

有什么解释吗?

最佳答案

有了这个代码

#include <iostream>
#include <cmath>
#include <cstdio>
using std::cout;

int mySqrt(int x) {
// For x = 2147395600
cout << exp(0.5*log(x)) << " "; // It prints 46340
return exp(0.5*log(x)); // But returns 46349
}

int main(void) {
std::cout << mySqrt(2147395600) << "\n";
printf("%.30f\n", exp(0.5*log(2147395600)));
return 0;
}

I got output:
46340  46339
46339.999999999978172127157449722290

传递给 cout时,该值似乎是四舍五入的;转换为 int时,该值被截断了。

关于c++ - C++ exp()函数确实有些奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61693232/

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