c - 为什么这个阶乘函数不起作用?
问题描述
我试图弄清楚如何自己做一个阶乘,所以它很乱,但我在某些方面感到困惑,比如这个。在 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 是用来结束函数的正确方法。
解决方案
就在这里,正如你提到的:
fact(&x, j); //this is what i mean, remove the "&" and it works, but why?
这是将一个指向 an 的指针int *
(或一个指向 an 的指针int
)传递给fact
.
因为x
是一个int
inmain
和一个int *
in fact
,你应该只从inside 传递x
到。fact
fact
当您*x
用于访问int
存储在x
insidefact
时,您应该使用x
来获取指向该 的指针int
。
如果它成功,则总是return 1
在函数的末尾,这样就if(func())
可以了。
作为旁注,您可能应该是return
从内部递归调用的结果fact
。
推荐阅读
- c# - 通过 GET 方法对 SAML Authn 请求的签名验证失败
- codenameone - 如何在加载时为 CN1 滑块进度设置动画
- sql-server - 不能在存储过程中调用函数
- mysql - 为什么像mysql中的查询同时使用索引和where条件?
- python-3.x - sqlite3 在 HDD 上似乎很慢
- c# - 2字节解压到4字节浮点数
- python - python blurwuzzy 比率服务器上的输出与本地计算机上的不同
- sublimetext3 - 强制 sublime 在 if/for 之后放置空间
- ios - 无法读取许可文件 LICENSE.txt - 创建 cocoapod
- bash - 如何停止 $ / 被剥离的字符串被插入到 sed 文件中?