怎么用while语句算5的阶乘?

while和for语句我觉得有点难!怎么才能完全理解并利用呢?

给你计算“n”的阶乘的方法,为了节省代码,并未对输入的n的合法性做判断,我想你应该会吧?
#include <iostream.h>
int step(int n)
{ int i=1;
static int j=1;
while(i<=n)
{ j=i*j;
i++;
}
return j;
}
int main()
{ int n;
cin>>n;
cout<<step(n)<<endl;
return 0;
}

while和for,我初学时也觉得难,但现在不敢说掌握很好,但也能解决一般的问题了;我的做法是:多做题!比如,我做的第一个循环题是——打印以下图形:
*
***
*****
*******
*********
*******
*****
***
*
当然,这个图形即使不用循环也能做出来,但要写不少代码,而且效率低下,所以我建议你能自己使用循环的方法做出来。只要多做练习,我想一定能掌握的!

注:不知怎的,图形和我想象的不同,应该是:
第一行4个空格,1个* 第二行3个空格,3个* 第三行2个空格,5个* 第四行1个空格,7个* 第五行没有空格,9个* ……再倒回去……但在“回答”里打不出来,希望你明白我的意思。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-02-22
给你个初学者很容易就看懂的用while语句来做的阶乘算法:
#include<iostream>
using namespace std;

int main()
{
int number; //这个number是待输入算阶乘的值
int result = 1; //用来存结果
cout<<"输个数"<<endl;
cin>>number;
if (number == 0)
result = 1;
else if(number >= 1)
{
while(number!=0)
{
result *= number;
number--;
}
}
else
cout<<"输入了错误的数值"<<endl;
cout<<"结果为"<<result<<endl;
return 0;
}
第2个回答  2008-02-21
#include <iostream.h>

int main()

{
int ina,i=1,num=0;
cout<<"请输入一个整数:";

cin>>ina;
if (ina>0)
{
//**************************************************
/*for (i=1;i<=ina;i++)
{
num=i*5;

cout<<"现在是:"<<i<<"*5="<<num<<"\n";
}*/
//**************************************************

//**********************************************************

i=0; //do while 需要定义这里..不然是从2开始了
do
{
i+=1;
num=i*5;

cout<<"现在是: "<<i<<"*5="<<num<<"\n";

} while (i<ina);

//***********************************************************

}

return 0;
}
第3个回答  2008-02-22
#include "iostream.h"

void main()
{
int a = 6;
int b = 1;
int c = 1;
while(b != a)
{
c = b * c;
++b;
}
cout << c << endl;
}
第4个回答  2008-02-22
不用while不用for

int main()
{
cout<<fut(5);
}

int fut(int s)
{
if(s>1)
return s*fut(s-1);
return s;
}
相似回答