Search code examples
c++floating-pointdoubleuser-inputcin

Why does the value slightly change when reading a huge double with std::cin?


I found a strange behavior of std::cin (using VS 17 under Win 10): when a large number is entered, the number that std::cin is reading is close but different. Is there any kind of approximation done with large numbers ? How to get the exact same large number than entered ?

double n(0);

cout << "Enter a number > 0 (0 to exit): ";
cin.clear();                                // does not help !
cin >> n;                                   // enter 2361235441021745907775
printf("Selected number %.0f \n", n);       // 2361235441021746151424 is processed ?.

Output

Enter a number > 0 (0 to exit):
2361235441021745907775
Selected number 2361235441021746151424

Solution

  • You need to learn about number of significant digits. A double can hold very large values, but it will only handle so many digits. Do a search for C++ doubles significant digits and read any of the 400 web pages that talk about it.

    If you need more digits than that, you need to use something other than double. If you know it's an integer, not floating point, you can use long long int which is at least 8 bytes and can hold 2^63-1. If you know it's a positive number, you can make it unsigned long long int and you get the range 0 to at least 18,446,744,073,709,551,615 (2^64-1).

    If you need even more digits, you need to find a library that supports arbitrarily long integers. A google for c++ arbitrary precision integer will give you some guidance.