实验结论
2-28 if...else
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{char a;
cout<<"Menu:A(dd) D(elete) S(ort) Q(uit),Select one:";
cin>>a;
while(true)
if (a=='A')
{cout<<"数据已经增加"<<endl;break;}
else if(a=='D')
{cout<<"数据已经删除"<<endl;break;}
else if (a=='S')
{cout<<"数据已经排序"<<endl;break; }
else if (a=='Q')
break;
else
{cout<<"error"<<endl;}
return 0; }
switch
#include <iostream>
using namespace std;
int main()
{ char c;
while (true)
{cout<<"Menu: A(dd) D(elect) S(ort) Q(uit) Select one: ";cin>>c;
switch(c)
{ case 'A':cout<<"数据已经增加"<<endl;continue;
case 'D':cout<<"数据已经减少"<<endl;continue;
case 'S':cout<<"数据已经排序"<<endl;continue;
case 'Q':break;
}
break;
}
return ;
}
2-29 while
#include <iostream>
#include <cmath>
using namespace std;
int main()
{ int n=,i,f,t=;
while(n<=)
{f=;
for(i=;i<=sqrt(n);i++)
if(n%i==)
{f=;
break;
}
if(f==)
{cout<<" "<<n;
t++;
if(t%==)
cout<<endl;
}
n++;
}
}
do...while
#include <iostream>
#include <cmath>
using namespace std;
int main()
{ int n=,i,f,t=;
do
{f=;
for(i=;i<=sqrt(n);i++)
if(n%i==)
{f=;
break;
}
if(f==)
{cout<<" "<<n;
t++;
if(t%==)
cout<<endl;
}
n++;
}while(n<=);
}
for
#include <iostream>
#include <cmath>
using namespace std;
int main()
{ int n=,i,f,t=;
for(;n<=;)
{f=;
for(i=;i<=sqrt(n);i++)
if(n%i==)
{f=;
break;
}
if(f==)
{cout<<" "<<n;
t++;
if(t%==)
cout<<endl;
}
n++;
}
}
2-32 while
#include <iostream>
using namespace std;
int main()
{ int n=,m;
cout<<"please guess the nunmber(1-100): ";cin>>m;
while(n!=m)
{if(m<n)
{cout<<"bigger than the number: ";cin>>m;}
else
{cout<<"smaller than the number: ";cin>>m;}
}
cout<<"You are right!"<<endl;
return ;
}
do...while
#include <iostream>
using namespace std;
int main()
{ int n=,m;
cout<<"please guess the nunmber(1-100): ";cin>>m;
do
{if(m<n)
{cout<<"bigger than the number: ";cin>>m;}
else
{cout<<"smaller than the number: ";cin>>m;}
}while(n!=m);
cout<<"You are right!"<<endl;
return ;
}
2-34
#include <iostream>
using namespace std;
int main()
{ int i,j,k,r=;
int c1,c2,c3;
cout<<"Red: 0,Yellow: 1,Blue: 2,White: 3,Black:4"<<endl;
int a[]={,,,,};
for(i=;i<=;i++)
{c1=a[i];
for(j=i+;j<=;j++)
{c2=a[j];
for(k=j+;k<=;k++)
{c3=a[k];
r++;
cout<<c1<<c2<<c3<<endl;}
c2=a[j];
}
c1=a[i];
}
cout<<"取法有:"<<r<<"种"<<endl;
return ;
}
实验总结与体会
格式与C语言有点区别,还是要学挺多东西的。穷举法不会。