I am making a program that adds the digits of a number but it does not give me the result I expect when placing an 11-digit number.
- Code
#include <iostream>
using namespace std;
int main() {
int extNum, sumDigit = 0, numEntero;
cout << "Ingrese un numero entero: ";
cin >> numEntero;
while(numEntero != 0) {
extNum = numEntero % 10;
numEntero /= 10;
sumDigit += extNum;
}
cout << "La suma de los digitos es: " << sumDigit << endl;
return 0;
}
Entry: 20483031154
Expected result: 31
Result obtained: 46
The number may not fit into the size of a
int
in your architecture.The
int
default type is usually 32 bits. The number you have entered, when put in binary requires 35 bits, so it does not fit and some kind of truncation will have occurred, altering the saved number and therefore the result.You can switch to a 64-bit integer (if your architecture allows it) with the declaration:
With this you will be able to use numbers as big as
18446744073709551615
, but beyond this you will find problems again.