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但仍然是相同的输出。
对此有什么解释吗?
有了这个代码
#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.
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |