C语言——输入一个非负整数n,返回组成它的数字之和

输入一个非负整数n,返回组成它的数字之和

eg.输入5167 输出19

  1. 思考

eg. 5167%10=7 5167/10%10=6 5167/100%10=1 5167/1000%10=5

5167 516 51 5

那我们怎么让5167除到第四位就不再往下除了呢?

即我们怎么让n除到最高位就不再往下除了?

当n/10<10时 不再往下除。

  1. 代码

#include<stdio.h>
int fun(int n)
{
if(n>9) return fun(n/10)+n%10;
else return n;
}

int main()
{int n;
scanf("%d",&n);
printf("%d\n",fun(n));
return 0;
}

猜你喜欢

转载自blog.csdn.net/outdated_socks/article/details/129307551