C ++ exp()函数确实很奇怪

问题描述 投票:3回答:1

试图在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,但输出仍然相同。

对此有任何解释吗?

c++ square-root exp
1个回答
2
投票

使用此代码

#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时,该值被截断了。

© www.soinside.com 2019 - 2024. All rights reserved.