2-28
(1)if....else
#include<iostream>
using namespace std;
int main()
{
char choice;
while(1)
{
cout<<"Menu:A(dd) D(elete) S(ort) Q(uit),Select one"<<endl;
do {
cin >> choice;
if (choice != 'A' && choice != 'D' && choice != 'S' && choice != 'Q')
{
cout << "Input error,please re-enter." << endl;
}
} while (choice != 'A' && choice != 'D' && choice != 'S' && choice != 'Q');
if(choice=='A')
{
cout<<"The data has incresed."<<endl;
continue;
}
else if(choice=='D')
{
cout<<"The data has deleted."<<endl;
continue;
}
else if(choice=='S')
{
cout<<"The data has sorted."<<endl;
continue;
}
else
{
cout<<"End......."<<endl;
break;
}
}
return 0;
}
(2)switch
#include<iostream>
using namespace std;
int main()
{
char choice;
while(1)
{
cout << "Menu:A(add) D(elete) S(ort) Q(uit),Select one:";
do {
cin >> choice;
if (choice != 'A' && choice != 'D' && choice != 'S' && choice != 'Q')
{
cout << "Input error,please re-enter." << endl;
}
} while (choice != 'A' && choice != 'D' && choice != 'S' && choice != 'Q');
switch (choice)
{
case 'A':
cout << "The data has been increased." << endl; break;
case 'D':
cout << "The data has been deleted." << endl; break;
case 'S':
cout << "The data has been sorted." << endl; break;
case 'Q':
break;
}
if (choice == 'Q')
{
break;
}
}
return 0;
}
2-29
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int i, j;
double a;
for (i = 2; i <= 100; i++)
{
a=sqrt(i);
for (j = 2; j <a; j++)
{
if (i%j == 0)
{
break;
}
}
if (j>a)
{
cout << i << endl;
}
}
return 0;
}
2-32 猜数游戏
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
char choice;
int aim;
int num;
while(1)
{
unsigned seed;
cout<<"please enter an unsigned integer"<<endl;
cin>>seed;
srand(seed);
aim=rand();
cout<<"please input one number..."<<endl;
cin>>num;
while(1)
{
if(num>aim)
{
cout<<"bigger.."<<endl;
cin>>num;
}
else if(num<aim)
{
cout<<"lowwer"<<endl;
cin>>num;
}
else
{
break;
}
}
cout<<"play again?(Y/N)"<<endl;
cin>>choice;
if(choice=='Y')
{
continue;
}
else
{
break;
}
}
return 0;
}
2-34 取球
#include<iostream>
using namespace std;
enum Color{red,yellow,bule,white,black
};
int main()
{
Color ball;
int i,j,k,t,sum=0;
for(i=red;i<=black;i++)
{
for(j=i+1;j<=black;j++)//避免出现重复
{
if(i==j)
{
break;
}
for(k=j+1;k<=black;k++)//同上,避免重复
{
if(k!=i&&k!=j)
{
sum+=1;
for(t=0;t<3;t++)
{
switch(t)
{
case 0:
ball=Color(i);break;
case 1:
ball=Color(j);break;
case 2:
ball=Color(k);break;
}
switch(ball)
{
case red:
cout<<"red ";break;
case yellow:
cout<<"yellow ";break;
case bule:
cout<<"bule ";break;
case white:
cout<<"white ";break;
case black:
cout<<"black ";break;
}
}
cout<<" "<<endl;
}
}
}
}
cout<<"一共有"<<sum<<"种方法"<<endl;
return 0;
}