简体   繁体   中英

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

I am calculating square 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.

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.)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM