题解 | #数位之和#
数位之和
https://www.nowcoder.com/practice/5e85cc26475449648e668aa98e92d05b
#include <stdio.h> int sum=0; //局部变量优先原则,若将sum初始化在num()里则只会输出个位数,因为每次递归sum都将被重新赋值为0; int num(int n) { //sum不可在这里初始化 if(n>9) { num(n/10); } sum=sum+n%10; return sum; } int main() { int n; scanf("%d",&n); sum=num(n); printf("%d\n",sum); return 0; }
加油!