C 递归程序无法使用 GCC 进行编译
#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;
}
我尝试过一些事情但无法让它发挥作用。我可能只是太累了,忽略了最小的事情,但非常感谢您的帮助!谢谢 :)
#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;
}
I've tried some things and can't get it to work. I could just be overtired and looking past the smallest thing but help would be much appreciated! Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能在
main()
或任何其他函数内部声明函数定义...函数定义必须是独立的,并且不能在其中嵌入函数定义。另外,我不确定您在标记为错误的行上做了什么,因为
f()
不是已定义的函数,因此您无法调用它。此外,它需要返回某种类型的左值,例如指向函数内部声明的静态变量的指针,或者通过引用传递给函数的指针,即使如此,语法也不正确,因为需要取消引用...所以基本上你不能做你在那条线上所做的事情。要获得可以编译的东西,请尝试
You cannot declare a function definition inside of
main()
or any other function ... function definitions have to be stand-alone and cannot have embedded function definitions inside of them.Also I'm not sure what you're doing on the line that you've marked as an error since
f()
is not a defined function, so you can't call it. Furthermore, it would need to return some type of l-value, such as a pointer to a static variable declared inside the function, or a pointer passed by reference to the function and even then the syntax is not right since there would be a required dereference ... so basically you can't do what you're doing on that line.To get something that compiles, try
使用缩进来查看范围可能存在的问题:
}
据我所知,C 没有闭包。
Use indentation to see possible problems with scope:
}
As far as I can remember, C doesn't have closures.
一个函数不能在另一个函数内部定义。然而 gcc 允许它作为扩展。您已经定义了一个名为
factorial
的函数,但尝试使用尚未在任何地方声明的f
。A function cannot be defined inside another function. However gcc allows it as an extension. You have defined a function named
factorial
but are trying to usef
which hasn't been declared anywhere.