简体   繁体   中英

Using sqrt function in c++

So, I am using sqrt function in c++ and the problem I am facing is, when the input to sqrt is 40000000001 , it returns 200000.

#include <iostream>
#include <cmath>

using namespace std;

int main (void)
{
    long long int a;
    cin>>a;
    double b = sqrt(a);
    cout<<b<<"\n";
    return 0;
}

Why is this happening?

It should return 200000.0000025 and I need this exact value. Even getting 200000 produces a Wrong answer. Thanks!

adding a

cout << "a=" << a << endl;

will reveal that when you enter 40000000001 the value of a is actually 46341. This is because to represent 40000000001 in an int you'll need 36 bits, while on your platform, int most likely only has 32 bits (31 plus one sign).

Using a long instead, I get 200000 as a result. The fact that you don't get 200000.0000025 must have to do with the fact that also doubles only have a limited amount of precision. Even though Wikipedia says that a 64 bit double has a precision of typically 15-17 decimal digits and the number you are looking for has 13 significant digits, I suspect there are roundoff errors in the intermediate steps of the calculation.


Part of the problem is also the printing, if you print for example:

    cout << b - 200000 << endl;

then I get

    2.49999e-06

as output which is very close to 0.0000025 . You can increase the number of digits which are printed:

    cout << setprecision(13) << b << endl;

which then prints 200000.0000025 on my platform.


If you need more precision than the primitive types provide, there are libraries to do that, see eg this list on Wikipedia . In particular, boost seems to have a library for that and here is an example taking a square root of a 100 digit number: Square root of a 100 digit number in C++

Use double instead of int , input value exceeded int max value .

#include <iostream>
#include <cmath> 
using namespace std;

int main()
{
    double a;
    cin >> a;
    double b = sqrt(a);
    cout << b << "\n";
}

You can use fixed , it make dipsplay unbrokenly.

   #include <iostream>
   #include <cmath>
   using namespace std;

    int main(void)
    {
        double a = 40000000001;
        cout << fixed << a << "\n";
        double b = (double )sqrt(a);
        cout << fixed <<b << "\n";
        return 0;
    }

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