#include <stdio.h>
int main (void)
{
int n, x;
int factorial (int n)
{
if (x<=0)
{
printf("x equals: ");
return 1;
}
else
{
return n * factorial (n-1);
}
f(x)=f(x-1)+2; //says error is here
}
return 0;
}
我已经尝试了一些东西,但无法让它工作。我可能只是太累了,忽略了最小的事情,但我将不胜感激!谢谢:)
最佳答案
您不能在 main()
或任何其他函数内声明函数定义...函数定义必须是独立的,并且不能在其中嵌入函数定义。
此外,我不确定您在标记为错误的行上做了什么,因为 f()
不是已定义的函数,因此您无法调用它。此外,它需要返回某种类型的左值,例如指向函数内声明的静态变量的指针,或者通过引用传递给函数的指针,即使这样语法也不正确,因为需要取消引用......所以基本上你不能做你在那条线上正在做的事情。
要得到可以编译的东西,试试
#include <stdio.h>
int factorial (int n)
{
if (n <= 0)
{
return 1;
}
else
{
return n * factorial (n-1);
}
}
int main (void)
{
int x;
x = factorial(5);
printf("Factorial of 5 is equal to %d", x);
return 0;
}
关于C 递归程序无法通过 GCC 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5900412/