c - I'm not getting any output in recursive function
问题描述
// this is a recursive function for finding the sum of digits in C language //I'm not getting any output in my IDE.
int dsum(int n)
{
int a, r;
r = n % 10;
a = r + dsum(n / 10);
return a;
}
int main()
{
int a;
a= dsum(12345);
printf("%d",a);
return 0;
}
解决方案
A recursion function should always have a base case as a final return, in this case it's when n equals 0, which means all digits were summed (when msb digit is divided by 10 the result is 0). Then you'll have the return which will call the function with the result of the current lsb digit (or right most digit) + the result of the function with the input of n/10
int dsum(int n)
{
if (n == 0) {
return 0;
}
return n % 10 + dsum(n / 10);
}
int main()
{
int a;
a = dsum(12345);
printf("%d",a);
return 0;
}
BTW, I also suggest looking into tail recursion: https://en.wikipedia.org/wiki/Tail_call
In this scenario, it might look like that:
int dsum_tail_recursion(int n, int sum)
{
if (n == 0) {
return sum;
}
return dsum_tail_recursion(n/10, n%10 + sum)
}
int main()
{
int a;
a = dsum_tail_recursion(12345, 0); // 0 is the sum start value
printf("%d",a);
return 0;
}
推荐阅读
- linux - Git over ssh:权限被拒绝公钥
- html - 带有 div 的 CSS 过渡持续时间不起作用
- python-3.x - 在网格中查找最大值的坐标
- httprequest - http/post 带有 :edn-params 的防伪令牌
- javascript - 从 JSON 映射嵌套数组以响应下拉列表
- excel - 在 Excel 中计算单元格
- java - 无法在里面找到元素
- javascript - forEach() 如何通过将文档作为文档数组的参数来返回值?
- tensorflow - 结合两个数据生成器来训练一个 CNN
- javascript - 如何更改 javascript 文件的输出格式?