我试图使用递归并将指针作为函数参数传递来找出数字的阶乘。但这个错误一直出现。调试器和编码器!我需要你的帮助。
The code
#include<stdio.h>
int *factorial(int *);
int value, p=0, q=1, x, tmp;
void main() {
int *result;
puts("Enter the value::");
scanf("%d",&value);
result = factorial(&value);
printf("\nThe Result is::%d\n", *result);
}
int *factorial(int *n) {
if(*n == p || *n == q) {
return(&q);
}
else {
tmp = *n -1;
*n *= (factorial(&tmp));
return(n);
}
}
The error:
error: invalid operands to binary * (have ‘int’ and ‘int *’)
*n *= (factorial(&tmp));
最佳答案
这一行:
*n *= (factorial(&tmp));
应该是
*n *= *(factorial(&tmp));
但是,请小心此实现,因为它是递归的,但使用指向全局变量的指针。
标准实现不适合您吗?
int factorial(int n)
{
if(n==0)
return 1;
else
return factorial(n-1)*n;
}
使用标准,您只需提示用户输入非负值。
关于c - 二进制 * 的无效操作数(有 ‘int’ 和 ‘int *’ ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26203322/