[英]Problem with square root of (2147483647) in c++
我正在通过sqrt函数计算2147483647的平方根,结果必须是浮点值46340.95,但是我的代码返回值46341。有人可以告诉我问题出在哪里吗? 我正在使用代码:
double x=2147483647.0;
double y=sqrt(x);
cout<< y;
我得到同样的结果。 但是,如果我注入一个setprecision
,我将得到正确的值:
#include <iostream>
#include <iomanip>
#include <cmath>
int main (void) {
double x=2147483647.0;
double y=sqrt(x);
std::cout << std::setprecision(10) << y << std::endl;
return 0;
}
给我:
46340.95
实际上,如果使用以下代码:
#include <iostream>
#include <iomanip>
#include <cmath>
int main (void) {
double x=2147483647.0;
double y=sqrt(x);
std::cout << y << std::endl;
std::cout << std::setprecision(0) << std::fixed << y << std::endl;
std::cout << std::setprecision(1) << std::fixed << y << std::endl;
std::cout << std::setprecision(2) << std::fixed << y << std::endl;
std::cout << std::setprecision(3) << std::fixed << y << std::endl;
return 0;
}
你得到:
46341
46341
46341.0
46340.95
46340.950
因此,默认设置(至少对于我的环境而言)的精度为零。
如果需要特定格式,建议您明确要求。
这个简单的代码将产生46340.9:
#include <cmath>
#include <iostream>
int main()
{
float x = std::sqrt(2147483647);
std::cout << x << std::endl;
return 0;
}
您的代码是什么样的?
(仅作记录:在MacOS X 10.6.6上使用GCC(g ++)4.5.2测试。)
cout
的默认精度不足以显示结果的小数部分。 您的结果为46340.95,四舍五入到六位数的精度为43641.0,并由cout
显示为43641。 要显示更高的精度,请先设置cout
的精度:
double x=2147483647.0;
double y=sqrt(x);
cout.precision(9);
cout<< y;
在我的系统上,该结果显示46340.95。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.