【发布时间】:2018-03-07 20:25:02
【问题描述】:
我想使用 Pass By Reference 方法创建一个递归阶乘。
int recursiveFactorialByValue(int x){
if (x==0||x==1) return 1;
else if (x<=0) return -1;
else return x * recursiveFactorialByValue(x-1);
}
void recursiveFactorialByReference(int *x){
int minusOne = *x - 1;
int *ptr = &minusOne;
if (*x==0||*x==1) *x = 1;
else if (*x <= 0) *x = -1;
else *x * recursiveFactorialByReference(ptr); //this is where the error occurs
}
int main(){
int x, *ptr=&x, **pptr=&ptr, y;
printf("Enter a positive integer: ");
scanf("%d",*&x);
y = x;
printf("%i! = %i\n",y,recursiveFactorialByValue(x));
recursiveFactorialByReference(ptr);
printf("%i! = %i\n", y, x);
return 0;
}
我收到此错误:
In function 'recursiveFactorialByReference':
14:7: error: void value not ignored as it ought to be
else recursiveFactorialByReference(ptr) * *x;
我尝试过不同的函数调用,例如:
否则 *x = *x * recursiveFactorialByReference(*x-1);
否则 *x = *x * recursiveFactorialByReference(ptr);
这些都不起作用,我找不到问题请帮忙。
【问题讨论】:
-
recursiveFactorialByReference不返回任何内容,因此*x * recursiveFactorialByReference(ptr);没有任何意义。 C也不支持按引用传递,您将指针作为参数(按值)传递
标签: c recursion parameters factorial