[英]Something really weird with C++ exp() function
在 C++ 中實現mySqrt function 時,我使用了 exp() function,如下所示:
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
}
我試圖用谷歌搜索這種行為的原因,但找不到任何東西。 我什至嘗試使用雙重但仍然相同的 output。
對此有何解釋?
使用此代碼
#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;
}
46340 46339
46339.999999999978172127157449722290
似乎該值在傳遞給cout
時被四舍五入,而在轉換為int
時被截斷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.