//寫一個遞歸函數(shù)DigitSum(n),輸入一個非負(fù)整數(shù),返回組成它的數(shù)字之和,
//例如,調(diào)用DigitSum(1729),則應(yīng)該返回1 + 7 + 2 + 9,它的和是19
//遞歸版
#include
int DigitSum(int n)
{
int sum = 0;
int m = 0;
if (n)
{
m = n % 10;
n = n / 10;
sum = m + DigitSum(n);
}
return sum;
}
int main()
{
int n = 0;
printf("請輸入你要轉(zhuǎn)換的數(shù):");
scanf("%d", &n);
int ret = DigitSum(n);
printf("各個位數(shù)和為:%d\n", ret);
return 0;
}
//非遞歸
#include
int DigitSum(int n)
{
int sum = 0;
int m = 0;
while (n)
{
m = n % 10;
n = n / 10;
sum = sum + m;
}
return sum;
}
int main()
{
int n = 1892;
int ret = DigitSum(n);
printf("%d\n", ret);
return 0;
}
網(wǎng)站題目:輸入一個非負(fù)整數(shù),返回組成它的數(shù)字之和
URL網(wǎng)址:
http://weahome.cn/article/peejsp.html