C++ exp() 函数真的很奇怪

Rak*_*hak 5 c++ square-root exp

在 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
}
Run Code Online (Sandbox Code Playgroud)

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

对此有什么解释吗?

Mik*_*CAT 6

有了这个代码

#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;
}
Run Code Online (Sandbox Code Playgroud)

我得到了输出

46340  46339
46339.999999999978172127157449722290
Run Code Online (Sandbox Code Playgroud)

似乎该值在传递给cout时四舍五入,而在转换为int.

  • 将浮点值(例如“double”)转换为整数类型(如“int”)会向零舍入。这是标准中规定的基本转换之一。 (3认同)
  • @Rakshak如果您想知道“46339.999999999978172127157449722290”的结果,那么这可能值得阅读:[每个程序员应该了解浮点运算](http://floating-point-gui.de/)。;-) (3认同)