c++ - 仅使用递归函数来计算给定数字的最终总和
问题描述
所以问题是:
**不能在递归函数中使用循环,仅用于输入检查
编写一个使用递归函数(或函数)的程序,该函数从用户那里接收一个正整数并计算他的数字的“最终数量”。
一个数字的最后一位数字的总和是一个过程的结果,在该过程中计算数字的数字总和,如果总和不是一位数字,则返回总和的数字,直到得到一位数字数字。
例子 :
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
{
}
}
解决方案
如果我很好理解 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;
}
推荐阅读
- spring - 错误“无法提取响应:没有找到适合响应类型 ... 和内容类型 [application/json] 的 HttpMessageConverter”
- omnet++ - 如何在 omnet++ Veins 中实现 RSU 到 RSU 的通信?
- google-colaboratory - 有没有其他方法可以在 Colab 中下载 kaggle 比赛数据?
- ruby-on-rails - 设置 Material UI 套件 React 时,Sass-Loader 的模块构建失败
- r - 如何在 R 中用 4 个变量绘制热图
- javascript - Recursive parse JSON tree in react native
- c - 使用 C 中的选项 -DDEBUG_HISTORY 在执行后检索内容变量的历史记录
- asp.net-mvc - 在 Azure 上成功部署后出错
- javascript - 如何定义可从类的所有方法访问的变量?
- image - 将 KMZ 文件上传到我的 Google 地图中,并在地标描述中添加图片