c - 我编写的这个程序的递归函数是什么,用于添加一个五位数的所有数字

标签 c

我无法为此编写递归函数,我在程序后给出了示例,

 #include<stdio.h>
 int sum(int x);
 int main()
{
   int n,s;
   printf("enter the five digit number whose digits need to be added");
   scanf("%d",&n);

   s= sum(n);

   printf("The sum of all the digits of a five digit number is %d",s);

}

int sum(int x)
{

  int d=0,a;

  for(i=1;i>=5;i++)
{
  a=x%10;
  x=x/10;
  d= d+a;  

}
  return(d);
}

下面是我自己编写的上述程序的递归代码,

#include<stdio.h>
int sum(int x);
int main()
 {

   int n,s;
   printf("enter the five digit number whose digits need to be added\n");
   scanf("%d",&n);

   s= sum(n);

   printf("The sum of all the digits of a five digit number %d",s);

}//This is my poor try inspired by coderedoc

//请修复此代码,我的笔记本电脑电池已经用完了

   int sum(int x)
  {
   int d=0, a;
   if(x<0)
   return sum(-x);
   else
   a= x%10;
   x= x/10;
   d=d+a;
   return sum(x);
   else
   if(x==0)
   return d;

   }

最佳答案

int sum(int x){
  if( x < 0) return sum(-x);
  return (x==0)?0:(x%10)+sum(x/10);
}

代码就这么简单。如果您到达 x=0 状态,您就完成了。否则将最后一位数字与其余数字的总和相加。

此外,在构建您的解决方案时 - 尝试使其在某种程度上具有普遍性。 5 数字很好,但请考虑是否可以将其扩展为更多数字。这也适用于此。

int sum(int x){
   if(x < 0) return sum(-x);
   if(x == 0)
       return 0;
   else
       return (x%10)+sum(x/10);
}

关于c - 我编写的这个程序的递归函数是什么,用于添加一个五位数的所有数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507480/

相关文章:

c - 如何在 C 文件中包含 gtk/gtk.h

c - 尝试使用 C 中的 SDL 从鼠标指针获取输入

c - 指针的使用

c++ - 使用按位运算符和 bool 逻辑的绝对值 abs(x)

c - 如何用 C 处理 PostgreSQL 中的数字数据类型?

c - 将魔数(Magic Number)分配给命名结构成员有什么问题?

c - 为什么这个程序中接收输入的两个提示显示在同一行?

c - Unix Socket - 客户端服务器程序(段错误)

c - 有多大的结构可以有效地按值传递?

c - 将函数调用为 fun() 和 fun 有什么区别?