写一个递归函数DigitSum(n),输入一个非负整数,返回组成它的数字之和,例如,调用DigitSum(1729),则应该返回1+7+2+9,它的和是19

#include<stdio.h>
#include<stdlib.h>
int fun(unsigned int n)
{
    if (n < 10)
    {
        return n;
    }
    else
    {
        return fun(n % 10) + fun(n / 10);
    }
}
int main()
{
    int num = 0;
    printf("请输入一个非负整数:");
    scanf_s("%d", &num);
    int ret = fun(num);
    printf("%d\n", ret);
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40995778/article/details/80294376