Hi. I need help with my code. It takes an integer as a parameter and returns the sum of the digits of the integer. I want my program to test if the integer is not too big to store or negative. I just can't wrap my head around it. Please be so kind to help.
#include <climits>
#include <cmath>
#include <iostream>
usingnamespace std;
void sumOfNumber();
int main()
{
char answer;
do
{
sumOfNumber();
cout << "\nOneMoreTime (Y/N) : ";
cin >> answer;
} while (answer == 'Y' || answer == 'y');
return 0;
}
void sumOfNumber()
{
int val, num, sum = 0;
cout << "Enter the number : ";
cin >> val;
num = val;
while (num != 0 && num <= INT_MAX)
{
sum = sum + num % 10;
num = num / 10;
}
cout << "The sum of the digits of the given number is " << sum;
}
Hi, thank you for your response.
I don't think I understand...
What I need help is how to make it test and return an error when the integer is negative or too large?
Hi. Thank you for response. Could someone help me with the full code? I don't seem to understand untill I see how it is built and I really have a hard time figuring it out for the past few days.
#include <iostream>
#include <climits>
enum result_t { OK, NOT_A_NUMBER, NEGATIVE, TOO_BIG } ;
result_t get_number( int& n )
{
n = 123456 ;
return ( std::cin >> n && n < 0 ) ? NEGATIVE : // input successful, and number is less than zero
( n == 0 && std::cin.fail() ) ? NOT_A_NUMBER : // input failed, and number was set to zero
( n == INT_MAX && std::cin.fail() ) ? TOO_BIG : // input failed, and number was set to INT_MAX
( n == INT_MIN && std::cin.fail() ) ? NEGATIVE : // input failed, and number was set to INT_MIN
OK ; // fine: input successful, and number is non-negative
}
int sum_digits( int number ) // invariant: non-negative n
{ return number < 10 ? number : ( number%10 + sum_digits( number/10 ) ) ; }
int main()
{
int number ;
std::cout << "enter a non-negative integer: " ;
const result_t result = get_number(number) ;
result == NOT_A_NUMBER ? ( std::cout << "error: input is not a number\n" ) :
result == NEGATIVE ? ( std::cout << "error: number is negative\n" ) :
result == TOO_BIG ? ( std::cout << "error: number is too big\n" ) :
( std::cout << "sum of digits: " << sum_digits(number) << '\n' ) ;
}