【发布时间】:2011-08-12 19:13:02
【问题描述】:
我试图编写一个函数,该函数将使用递归计算数字的数字之和,但输出不正确。代码如下:
/*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);
}
以下是一些输出值:
udit@udit-Dabba ~/Desktop/letusc/ch5/J $ ./a2.out
Enter the number:123
The sum of the digits of the number is 7
udit@udit-Dabba ~/Desktop/letusc/ch5/J $ ./a2.out
Enter the number:1234
The sum of the digits of the number is 2919930
udit@udit-Dabba ~/Desktop/letusc/ch5/J $ ./a2.out
Enter the number:123456
The sum of the digits of the number is 4620297
udit@udit-Dabba ~/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 位数字会给出错误的结果。
-
输出是什么?请编辑您的问题以包括示例输入、预期输出和实际输出。
-
这不是论坛。问题就像 wiki 一样工作。 请将输出放入您的问题中。
-
您希望为负输入 (-123) 返回什么值?
-
@Jonathan:可能 OP 应该简单地更改函数签名以使用无符号类型。 :-)