Hey everyone. I wrote this code in order to successfully determine all the digits of a number as well as the sum. However, here is the output of the code:
2+4+5+11
I want my code to process the following output:
2+4+5=11
Is there any way this can get fixed? Any response would help a lot. Thanks.
#include <iostream>
using namespace std;
int sumofDigits(int n) {
if (n < 10) return n;
else return (n % 10) + sumofDigits(n / 10);
}
void listofDigits(int n) {
if (n <= 0) return;
listofDigits(n / 10);
cout << n % 10;
if (n >= 0) cout << "+";
else cout << "=";
}
int main() {
int n = 245;
listofDigits(n);
cout << sumofDigits(n);
}
#include <iostream>
#include <string>
usingnamespace std;
void sumDigits( int n )
{
string S = to_string( n );
int sum = 0;
for ( char c : S )
{
cout << ( sum ? "+" :"" ) << c;
sum += c - '0';
}
cout << "=" << sum << '\n';
}
int main()
{
sumDigits( 245 );
}