仅使用递归函数来计算给定数字的最终总和
Using recursion functions only to calculate the final sum of a given number
所以问题是:
**不能在递归函数中使用循环,仅用于输入检查
编写一个使用递归函数(或函数)的程序,该函数从用户那里接收正整数并计算其数字的"最终数量"。
数字最后一位数字的总和是一个过程的结果,在这个过程中,计算数字的位数之和,如果总和不是一位数,则返回总和的位数,直到得到一个数字。
例:
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;
}
相关文章:
- 如何编写一个递归函数,以随机的方式混淆从0到6的数字
- 递归函数有助于显示反向数字
- 递归函数用于计算 n 个数字之和的意外输出
- 编写一个函数,用递归函数检查数字是否是正方形
- 递归函数,用于计算数字中的位数
- 仅使用递归函数来计算给定数字的最终总和
- 为数字序列创建递归函数
- 设计生成所有 n 位数字组合的递归函数的最佳方法是什么?
- 如何在递归函数中更改数字的数字?C++
- 递归函数,用于查找数字的幂
- 用于检查数字的递归函数
- 递归函数不附加数字
- 有没有办法将 int 赋入具有递归函数的字符串中,而无需将数字反转两次
- 尝试优化和理解打印数字除数的递归函数的运行时
- 在递归函数中查找最大数字
- 加泰罗尼亚数字,递归函数时间复杂度
- 尾递归函数,用于计算数组中大于平均值的所有数字
- c++中使用多个数字的LCM递归函数
- 增加递归函数中的数字
- 使用递归函数从数组输出的数字与输入的数字不同