首页 > 解决方案 > 仅使用递归函数来计算给定数字的最终总和

问题描述

所以问题是:

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

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

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

例子 :

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

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

生物信息学学生,尝试在 main 中使用 if 条件,但想不出好东西。

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

    }

}

标签: c++

解决方案


如果我很好理解 sum 就是这样:

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

推荐阅读