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);
}
不知道错在哪里了..麻烦大虾们帮帮忙

第1个回答  2011-05-18
没错按道理来说是 不满足 条件 (n>1) 时才执行 return 1;
加上 else 程序看起来更清楚。

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

所以 else 就可以省略了,只有 不满足 条件 (n>1) 时才会执行到 return 1;
第2个回答  2011-05-17
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$
程序已调好,直接运行即可。追问

那如果我要在程序中自己输入一个数,然后得到结果应该怎么改呢?

追答

main函数改一下:
int main()
{
int n=0;
scanf("%d",&n);
printf("the n! is %d:\n",fun(n));//你调用函数的时候格式不对,而且也没传参数。
return 0;
}

第3个回答  2011-05-17
#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));
}追问

那如果我要在程序中自己输入一个数,然后得到结果应该怎么改呢?

追答

不要输入太大的数字,阶乘的增长速度很快,大了表示不了
#include "stdio.h"
int fun(int n)
{
if (n==1)
return 1;
else
return n*fun(n-1);
}
main()
{
int n;

scanf("%d", &n);

printf("the n! is %d: \n",fun(n));
}

本回答被提问者采纳
第4个回答  2011-05-17
大哥,函数分有参和无参函数,你定义的这个函数唯有参函数,所以调用时,需要传递参数的
int fun(int n)
调用时如fun(9);等等的
希望可以帮助到你追问

那如果我要在程序中自己输入一个数,然后得到结果应该怎么改呢?

追答

#include "stdio.h"
int fun(int n)
{
int t=1;
if (n==1)
t=1;
else
t=n*fun(n-1);
return t;
}
main()
{
int a;
scanf("%d",&a); //读入一个数
printf("the n! is %d:\n",fun(a)); //进行函数调用,fun(a),参数传递。
}
//你的意思是想输入一个数求阶乘吧?

第5个回答  2011-05-17
fun调用的时候要给出一个参数,int型的
printf("the n! is %d:",fun(5));比如这样

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网