I'm having a problem with my program. When I input 1234, I get the correct display: 1 2 3 4 and the sum is 10.
However, when I input more than 4 numbers, the display is wrong and therefore it adds the wrong numbers. I can't figure out what's wrong.
#include <iomanip>
#include <iostream>
#include<cmath>
usingnamespace std;
int mainudf();
int main ()
{
mainudf();
}
int mainudf()
{
int number;
int i = 0;
int digit = 0;
int sum = 0;
cout << "This program will accept an integer and output the individual numbers of the integer. \n"
<< "It will then display the sum of the individual digits.\n"
<< "Please enter an integer" << endl;
cin >> number;
cout << endl;
number = abs ( number ); // takes the abs value of the number so negative numbers can be used.
int copynumber = number; // storing the number into a diff variable
// Find the number of digits
do
{
i ++;
copynumber = copynumber / 10;
}
while ( copynumber != 0 );
//using the power function to remove digits from the number
int divisor = pow ( 10 , i - 1 );
// Take out each digit from the left, calculate sum and print the digit
do
{
digit = number / divisor; // Take out a digit
number = number - ( digit * divisor ); // Update integer
cout << digit << ' ';
sum = sum + digit;
divisor /= 10; // Take a zero off the divisor
}
while ( divisor > 0 );
cout << "\nSum = " << sum << endl;
return 0;
}
When I use the online cpp.sh enviroment, it still does not work for large numbers:
1 2 3 4 5 6 7 8
This program will accept an integer and output the individual numbers of the integer.
It will then display the sum of the individual digits.
Please enter an integer
56164989879
2 1 4 7 4 8 3 6 4 7
Sum = 46
When using codeblocks, it does not work for numbers over four digits:
1 2 3 4 5 6 7
This program will accept an integer and output the individual numbers of the integer.
It will then display the sum of the individual digits.
Please enter an integer
12345
1235
Sum = 11