仅使用递归函数来计算给定数字的最终总和

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

本文关键字:数字 递归函数 计算      更新时间:2023-10-16

所以问题是:

**不能在递归函数中使用循环,仅用于输入检查

编写一个使用递归函数(或函数)的程序,该函数从用户那里接收正整数并计算其数字的"最终数量"。

数字最后一位数字

的总和是一个过程的结果,在这个过程中,计算数字的位数之和,如果总和不是一位数,则返回总和的位数,直到得到一个数字。

例:

96437 的数字之和是 29 9 + 6 + 4 + 3 + 7 = 29 29 的数字之和是 11 2 + 9 = 11 11 的数字之和是 2 1 + 1 = 2

我想到了如何使用递归来计算数字的总和,但不知道如何设置正确的条件来做到这一点,因此它将是一个位数的数字。

生物信息学的学生,试图使用如果条件在主要,但想不出好的东西。

 #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
    {
    }
}

如果我很好地理解总和就是:

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;
}