我試圖編寫一個函數來計算使用遞歸的數字的數字總和,但輸出不正確。下面的代碼:遞歸函數的輸出不正確以計算數字的總和
/*Write a function to calculate sum of digits of a number using recursion*/
/*Author:Udit Gupta Date:10/08/2011*/
#include<stdio.h>
int sum (int);
int main() {
int n,s;
printf ("Enter the number:");
scanf ("%d",&n);
s = sum (n);
printf ("The sum of the digits of the number is %d",s);
}
int sum (int a) {
int f;
if (a == 0) {
return f;
}
f = (a% 10) + sum (a/10);
}
下面是一些輸出值:
[email protected] ~/Desktop/letusc/ch5/J $ ./a2.out
Enter the number:123
The sum of the digits of the number is 7
[email protected] ~/Desktop/letusc/ch5/J $ ./a2.out
Enter the number:1234
The sum of the digits of the number is 2919930
[email protected] ~/Desktop/letusc/ch5/J $ ./a2.out
Enter the number:123456
The sum of the digits of the number is 4620297
[email protected] ~/Desktop/letusc/ch5/J $ ./a2.out
Enter the number:12345
The sum of the digits of the number is 15 /*Only this one seems correct*/
有人可以幫助我弄清楚這是爲什麼不能正常工作?
對於5位數字的輸出是正確的,但在5位數字的上方和下方輸出是錯誤的結果。 –
輸出是什麼?請編輯您的問題以包含樣本輸入,預期輸出和實際輸出。 –
這不是一個論壇。問題像維基一樣工作。 *請輸出您的問題。* –