文档介绍:实验3 循环程序设计
【实验目的】
1掌握循环结构while、do-while、for的使用。
2了解转向语句的使用。
3学习循环结构的嵌套使用。
【实验内容】
⒈编写程序用公式
计算e的近似值。直到最后一项小于给定精度。
#include <>
void main()
{
double e = ,x = ,y,z;
int n=1;
cout<< "input 精度:";
cin>>z ;
y=1/x ;
while(y>=z){
x*=n;
y=1/x;
e+=y;
++n;}
cout<<e<<endl;
}
⒉有一对兔子,从第三个月起每个月生一对兔子,小兔子从第三个月起每个月又生一对兔子,假设所有兔子都不死,编程序计算每个月的兔子是多少对(求20个月)。
#include <>
void main( )
{ int f1,f2,f3;
int i;
f1=f2=1;
for(i=3;i<=20;i++){
f3=f1+f2;
cout<<i<<"月兔子对数为:"<<f3<<endl;
f1=f2;
f2=f3;}
}
⒊编写程序打印如图3-1所示蝶形图形。
# include <>
void main()
{ int i,j,k,d;
for(i=-3;i<=3;i++){
cout<<endl;
d=i;
if (i<0) d=-i;
for (j=1;j<=10-3*d;j++)
cout<<" ";
for (k=1;k<=6*d+3;k++)
cout<<"B"; }
cout<<endl;
}
⒋从键盘输入任意多个整数(-999为结束标志),计算其中正数之和。
#include <>
void main()
{ int x,s=0;
while(1){
cin>>x;
if (x==-999) break;
if (x<0) continue;
s=s+x;
}
cout<<"s="<<s<<endl;
}
⒌ 编程序打印一个如图3-2所示的数字金字塔:(选作题)
# include <>
void main()
{ int i,j,k,m;
for(i=1;i<=9;i++)
{
{ for (j=1;j<=9-i;j++)
cout<<" ";
for (k=1;k<=i;k++)
cout<<k;
for (m=i-1;m>=1;m--)
cout<<m;
}
cout<<endl;
}
}
⒍课本的第9题
⑴#include <>
#include <>
void main()
{cout <<" *";
for(int i=1; i<=9; i++)
cout <<setw(4) <<i;
cout <<"\n---------------------------------------