sha*_*dra 1 c algorithm recursion
我正在做一个简单的程序C,5位数字的数字之和.虽然我用一个简单的函数完成它但我也需要用递归来做.我已经在网上阅读了很多关于这个问题的解决方案,使用递归和已经实现了我的一个.但这是错误的,我无法弄清楚我在算法中做了什么网格.
#include<stdio.h>
int sum5(int x); //function for sum of digits of 5 digit number
int main()
{
int x;
int result;
printf("Enter a 5 digit number : ");
scanf("%d",&x);
printf("Number entered by you is %d",x);
result = sum5(x);
printf("Sum of digits of 5 digit number is = %d",&result);
return 0;
}
int sum5(int x)
{
int r;
int sum=0;
if(x!=0){
r=x%10;
sum=sum+r;
x=x-r; //doing this so that 0 come in the last and on diving it by 10, one digit will be removed.
sum5(x/10);
}
return sum;
}
Run Code Online (Sandbox Code Playgroud)
但在执行后我得到了错误的结果.它在输出上倾倒了一些匿名值.
这是不正确的,它是打印地址的result,而不是它的价值:
printf("Sum of digits of 5 digit number is = %d",&result);
Run Code Online (Sandbox Code Playgroud)
改成:
printf("Sum of digits of 5 digit number is = %d", result);
Run Code Online (Sandbox Code Playgroud)
始终检查结果scanf()以确保读取有效值:
/* Returns number of assignments made. */
if (scanf("%d", &x) == 1 && x > 9999 && x < 100000)
{
}
Run Code Online (Sandbox Code Playgroud)
加上Osiris
sum5()指出的执行错误.
此外,您的sum5功能不正确.您必须将值添加sum5到sum调用方函数的变量中.
int sum5(int x)
{
int r;
int sum = 0;
if (x != 0) {
r = x % 10;
sum = r;
//x = x - r; - this isn't required. integer division will floor x
sum += sum5(x / 10);
}
return sum;
}
Run Code Online (Sandbox Code Playgroud)