0

I'm trying to get the last digit of entered value in C++. Why the output is always 7 or 5 when I enter a big number e.g. 645177858745?

#include <iostream>
using namespace std;

int main()
{
    int a;
    cout << "Enter a number: ";
    cin >> a;
    a = a % 10;
    cout << "Last Number is " << a;
    return 0;
}

Output:

Enter a number: 8698184618951

Last Number is 5

JaMiT
  • 14,422
  • 4
  • 15
  • 31
  • That number is too large to fit in an int. Always check if your input succeeded before you do anything with it. `if (cin >> a) { /* success, do whatever */ } else { /* handle failure */ }` – Retired Ninja Nov 07 '21 at 03:48
  • What happens if you hardcode your value instead of reading it from the user? That is, replace `int a; cout << "Enter a number: "; cin >> a;` with `int a = 8698184618951;`. Any complaints [or warnings](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) from your compiler? – JaMiT Nov 07 '21 at 03:50
  • @JaMiT that case is implementation-defined and may give different results to the stream extraction operation – M.M Nov 07 '21 at 04:00
  • @M.M The point is not the numerical result. The point is getting a warning from the compiler (which is why I specifically asked about warnings). Is there a major compiler that does *not* warn when assigning too large a value to an `int` (assuming common warnings have been turned on)? *Side note: this happens to also serve as a test to see if the OP is on an unusual system where `int` actually is large enough to store 8698184618951 and the problem is something else, something we don't see.* – JaMiT Nov 07 '21 at 04:06

2 Answers2

0

The largest value that an int (on most machines) can hold is 2147483647

You enter 8698184618951, which is bigger than 2147483647. Because an int can't hold 8698184618951, extraction will fail but a will now be the max value that it can hold. So a is now 2147483647.

You should use a bigger type, like long long instead of int

So your code should look like this:

#include <iostream>
// using namespace std; is bad

int main()
{
    long long a;
    std::cout << "Enter a number: ";
    std::cin >> a;
    a = a % 10;
    std::cout << "Last Number is " << a;
    return 0;
}
0

If the value read is out of range for the integer type, then extraction fails but a is set to the maximum (or minimum) value of the type.

The size of int is implementation-defined but its maximum value should end in 7 for any common systems. If the exact code and input that you posted actually gives 5 then it could either be a compiler bug, or an old compiler. (Prior to the publication of the C++11 standard this behaviour was not mandated). The 5 might be seen for a similar case but extracting to unsigned integer.

M.M
  • 138,810
  • 21
  • 208
  • 365