再帰を使用して数値の桁の合計を計算する関数を作成しようとしましたが、出力が正しくありません。ここで、コードは次のとおりです。ここで数値の桁の合計を計算する再帰関数の出力が正しくない
/*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桁の数値の上と下は間違った結果になります。 –
出力は何ですか?サンプル入力、予想される出力、実際の出力を含めるように質問を編集してください。 –
これはフォーラムではありません。質問はウィキのように機能します。 *あなたの質問に出力を入れてください。* –