问个简单的问题,一个数的阶乘的。

huangmaomao 2003-10-17 01:14:11
昨天没调出来
觉得太简单都不好意思问了
不要笑话我啊
我的程序
#include <iostream.h>

int fact (int n);

int main()
{int x;
do
{
cin>>x;
cout<<"(x!)="<<fact(x)<<endl;
}
while(x!=0);
return 0;
}

int fact (int n)
{int m,n;
for(n;n=0;n--)
m*=n;
return m;
}
提示让我重新定义形参n
还有个问题 就是我看的书上是 #include"iostream" 为什么我在VC6和BC3。0下必须写成iostream.h呢?
...全文
39 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Hot_Forever 2003-10-17
  • 打赏
  • 举报
回复
我改的程序,仅供参考
int fact(int n)
{
int result=1;
if(n==0) return 1; //0!=1
else
{
for(int m=1;m<=n;m++)
result*=m;
}
return result;
}

#include <iostream.h>
int main()
{
int x;
while(cin>>x)
cout<<x<<"!="<<fact(x)<<endl;
return 0;
}
njSeeWhy 2003-10-17
  • 打赏
  • 举报
回复
楼上的,不好意思,现在的标准库后面都不加.h的后缀名的。符合标准的写法应该是:
#include <iostream>
using namespace std;

// other codes here;
另外,搂主的fact函数写的不对,你写的是
int fact (int n)
{int m,n; // 这里错了
for(n;n=0;n--) // 这里也错了!
m*=n;
return m;
}
应该写成:
int fact (int n)
{int m=1; //不要再声明n了,n已经作为参数传进来了,另外,m要初始化成1,不然怎么累乘?
for(;n>0;n--) // n已经有初始值了,所以for的第一个分号前面不需要有东西。从n乘到1,就
//是n!了,对吧
m*=n;
return m;
}
这样改过就可以了,完整的程序是:
#include <iostream>
using namespace std;

int fact (int n);

int main()
{int x;
do
{
cin>>x;
cout<<"(x!)="<<fact(x)<<endl;
}
while(x!=0);
return 0;
}

int fact (int n)
{int m=1;
for(;n>0;n--)
m*=n;
return m;
}


Bandry 2003-10-17
  • 打赏
  • 举报
回复
形参和局部变量重名了啊
你看的书是最新标准,VC6不支持!
pxwzd123 2003-10-17
  • 打赏
  • 举报
回复
帮你改了一下,可以了
#include <iostream.h>

int fact (int n);

int main()
{int x;

while(1){
cin>>x;
if(x<=0)
break;
cout<<"(x!)="<<fact(x)<<endl;
}
return 0;
}

int fact (int n)
{int m,result=1;

for(m=1;m<=n;m++)
result*=m;
return result;
}
你看的书是采用以前的标准,VC6.0下要加.h后缀名

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧