求整数的各位数字之和
编译器vs2022
(scanf没有错误)
想写个自定义函数实现求和
#include<stdio.h>
int shuzihe(int y);
int main()
{
int n;
scanf_s("%d", &n);
printf("%d", shuzihe(n));
return 0;
}
int shuzihe(int y)
{
int result;
if (y == 0)
result = 0;
else if (y % 10 != 0)
result = shuzihe(y);
return result;
}
递归这样写不死循环才怪?想用变量的话这样:
#include<stdio.h>
int shuzihe(int y);
int main()
{
int n;
scanf("%d", &n);
printf("%d", shuzihe(n));
return 0;
}
int shuzihe(int y)
{
if (y == 0) {
return 0;
}
return y % 10 + shuzihe(y / 10);
}
递归里y没有变化,死循环