首页 > 解决方案 > 为什么这个阶乘函数不起作用?

问题描述

我试图弄清楚如何自己做一个阶乘,所以它很乱,但我在某些方面感到困惑,比如这个。在 fact() 我输入fact(x,j). 这有效。但是我最初的尝试fact(&x,j)没有奏效。这是为什么?后一个参数不应该起作用吗,因为我正在发送 x 的地址,我已经将它设置为 n*n-1 in*x = (*x)*j;

int main(void)
{
    int x =0;
    scanf("%d", &x);
    int j =x;
    fact(&x, j);
    printf("%d\n", x);
    scanf("%d", &x);
}

int fact(int *x, int j)
{
    if(j!=1)
    {
        j = j-1;
        *x = (*x)*j;
        printf("j is : %d\n", j);
        fact(&x, j); //this is what i mean, remove the "&" and it works, but why?
    } else if(j==1)
    {
        return 0;
    }
}

如果x是一个指针,并&x给出了位置,为什么我&x在 main 中使用但只x在函数内部使用?

也不确定 return 0 或 return 1 是用来结束函数的正确方法。

标签: c

解决方案


就在这里,正如你提到的:

fact(&x, j); //this is what i mean, remove the "&" and it works, but why?

这是将一个指向 an 的指针int *(或一个指向 an 的指针int)传递给fact.

因为x是一个intinmain和一个int *in fact,你应该只从inside 传递x到。factfact

当您*x用于访问int存储在xinsidefact时,您应该使用x来获取指向该 的指针int

如果它成功,则总是return 1在函数的末尾,这样就if(func())可以了。

作为旁注,您可能应该是return从内部递归调用的结果fact


推荐阅读