Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

c++ - Using recursion functions only to calculate the final sum of a given number

so the question is:

**cant use loops in the recursive functions, only for input check

Write a program that uses a recursive function (or function) that receives a positive integer from the user and calculates the "final amount" of his digits.

The sum of the final digits of a number is the result of a process in which calculates the sum of digits of the number and if the sum is not a single digit number and return the sum the digits of the sum until you get a single digit number.

example :

The sum of the digits of 96437 is 29 9 + 6 + 4 + 3 + 7 = 29 And the sum of the digits of 29 is 11 2 + 9 = 11 And the sum of the digits of 11 is 2 1 + 1 = 2

I figured how to use recursion to calculate sum of a number but dont know how to put the right condition to do it so it will be single digit number.

Student for bioinformatics, tried to use if condition in main but cant think of something good.

 #include <iostream>
using namespace std;

// recursive function to find sum of digits of a number
int sum(int x)
{
    if (x == 0)
    {
        return 1;
    }
    return (x % 10 + sum(x / 10));
}


int main()
{
    int n, result;
    // input and input check for positive number
    do{
        cout << "Please enter a positive number:"<< endl;
        cin >> n;
        cout << endl;
    } while (n <= 0);

    result = sum(n);
    if (result % 10 == 0)
    {
        cout << result << endl;
    }
    else
    {

    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

if I well understand sum is just that :

int sum(int n)
{
  return (n <= 9)
    ? n // the sum is the number itself
    : sum((n % 10) + sum(n / 10));
}


int main()
{
   int n;
   // input and input check for positive number
   do{
      cout << "Please enter a positive number:"<< endl;
      cin >> n;
      cout << endl;
   } while (n <= 0);

   cout << sum(n) << endl;

   return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...