开发者

Problem with square root of (2147483647) in c++

I am calculating s开发者_如何转开发quare root of 2147483647 by sqrt function.and the result must be a float value 46340.95 but my code returns the value 46341. Can anyone tell me where is the problem? i am using code :

double x=2147483647.0;
double y=sqrt(x);
cout<< y;


I get that same result. But, if I inject a setprecision, I get the right value:

#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;
}

gives me:

46340.95

In fact, if you use the folowing code:

#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;
}

you get:

46341
46341
46341.0
46340.95
46340.950

So it appears that the default setting (at least for my environment) is a precision of zero.

If you want a specific format, I suggest you explicitly request it.


The default precision for cout is not sufficient to show the fractional part of your result. Your result is 46340.95, which rounded to six digits of precision is 43641.0, and is displayed as 43641 by cout. To show more precision, set the precision of cout first:

double x=2147483647.0;
double y=sqrt(x);
cout.precision(9);
cout<< y;

On my system this shows a result of 46340.95.


This trivial code yields 46340.9:

#include <cmath>
#include <iostream>

int main()
{
    float x = std::sqrt(2147483647);
    std::cout << x << std::endl;
    return 0;
}

What does your code look like?

(Just for the record: tested using GCC (g++) 4.5.2 on MacOS X 10.6.6.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜