c -递归函数在计算数字的位数和时输出不正确



我试图编写一个函数,该函数将使用递归计算数字的数字之和,但输出是不正确的。下面是代码:

/*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*/

有人能帮我弄清楚为什么这不能正常工作吗?

让我们更详细地看看这个递归函数:

int sum (int a) {
    int f;
    if (a == 0)
        return f;
    f = (a% 10) + sum (a/10);
}

当你在正确的轨道上并且你有正确的想法时,你的实际实现有点错误。对于初学者,让我们看看这些行:

if (a == 0)
    return f;

a达到0时终止递归的想法是正确的,但是你这样做的方式有点偏离。具体来说,您返回的是整数f的值,但您从未初始化它。这意味着返回值完全是任意的。我想你应该写一些更接近

的东西,而不是这样写。
if (a == 0)
    return 0;

正确地表示"如果数字为零,其数字之和为零。"

同样,看一下函数的最后一行:

f = (a% 10) + sum (a/10);

再一次,你的直觉是正确的:一个数字的数字的和是由它的第一位数字和其他数字的和给出的。然而,请注意,当您正确地计算数字的总和时,您没有正确地返回数字的总和。实际上,如果执行这段代码,您根本不会返回任何东西,因此函数的返回值是未指定的,因此是垃圾输出。要解决这个问题,可以考虑像这样重写代码:

return (a % 10) + sum (a / 10);

这实际上是说要返回刚才生成的值,而不是将其存储在一个局部变量中,该局部变量将在函数返回时立即被清理。

我相信你以这种方式编码这个函数的原因是你认为int f;的值是在函数调用中携带的。不幸的是,事实并非如此。在编写递归函数时,函数的每个实例完全独立于其他实例,并且在一个递归调用中可访问的局部变量在其他递归调用中不可访问。因此,尽管每个递归调用都有自己的变量int f,但这些变量都是完全相互独立的。值不通过它们传递。如果你想在递归函数之间传递值,最好的方法是使用递归调用的返回值,或者(如果必须的话)通过递归传递一个指向某个值的指针。

希望这对你有帮助!

当a为0时,返回一个未初始化的值(f未初始化)

改为:

if (a == 0)
        return 0;

您还忘记了函数末尾的返回:

return (a% 10) + sum (a/10);

强烈建议您总是使用-Wall标志进行编译,它会警告您这些错误

你的递归函数将不计算任何东西——它要么返回一个未初始化的int,要么什么都不返回。您需要返回您在函数中所做的工作。

int sum (int a) {
  if (a == 0) {
    return 0;
  }
  return (a% 10) + sum(a/10);
}
return a == 0 ? 0 : ((a% 10) + sum (a/10));

只有当它为0时才返回f,如果它不为0则不返回,这使得返回值未定义。我猜你想做:

int sum (int a) {
    int f;
    if (a == 0)
        return 0;
    f = (a % 10) + sum (a / 10);
    return f;
}

最新更新