当前位置:编程学习 > C/C++ >>

C语言递归求阶乘求改错

#include "stdio.h" int fun(int n) { int t=1; if (n==1) t=1; else t=n*fun(n-1); return t; } main() { printf("the n! is %d:",fun); } 不知道错在哪里了..麻烦大虾们帮帮忙
追问:那如果我要在程序中自己输入一个数,然后得到结果应该怎么改呢?那如果我要在程序中自己输入一个数,然后得到结果应该怎么改呢?那如果我要在程序中自己输入一个数,然后得到结果应该怎么改呢?
答案:#include "stdio.h"
int fun(int n)
{
	if (n==1)
		return 1;
   else 
	   return n*fun(n-1);
}
main()
{
	printf("the n! is %d: \n",fun(6));
}
其他:zxsh@zxsh-laptop:~/code/tmp$ cat factory.c
#include "stdio.h"
int fun(int n)
{
	int t=1;
	if (n==1||n==0)//增加一个n==0的情况。因为阶乘定义规定0的阶乘为1
		t=1;
   else 
	   t=n*fun(n-1);
   return t;
}
int main()
{
	printf("the n! is %d:\n",fun(5));//你调用函数的时候格式不对,而且也没传参数。
return 0;
}
zxsh@zxsh-laptop:~/code/tmp$ !g
gcc -g -Wall factory.c -o factory
zxsh@zxsh-laptop:~/code/tmp$ ./factory 
the n! is 120:
zxsh@zxsh-laptop:~/code/tmp$ 
程序已调好,直接运行即可。 fun调用的时候要给出一个参数,int型的
printf("the n! is %d:",fun(5));比如这样 大哥,函数分有参和无参函数,你定义的这个函数唯有参函数,所以调用时,需要传递参数的
int fun(int n)
调用时如fun(9);等等的
希望可以帮助到你 #include "stdio.h"
int fun(int n)
{
    return n <= 1 ? 1 : fun(n-1) * n;
}
int main()
{
	printf("the n! is %d:",fun(10));
} 没错按道理来说是 不满足 条件 (n>1) 时才执行 return 1;
加上 else 程序看起来更清楚。

可是 因为  满足 条件 (n>1) 时执行的是
return (n*fun(n-1)); 
就已经退出函数了

所以 else 就可以省略了,只有 不满足 条件 (n>1) 时才会执行到 return 1;
 

上一个:c语言程序问题 输入5个学生 5 门课的成绩,分别用函数求三个结果。程序已附上,看看哪出错了?
下一个:请求各位C语言高手,C语言问题 :

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,