Home > OS >  The last digit of entered value is always 7 or 5 when entering a big number
The last digit of entered value is always 7 or 5 when entering a big number

Time:11-07

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

CodePudding user response:

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.

CodePudding user response:

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;
}
  •  Tags:  
  • c
  • Related