#includeusing namespace std; int main() { char a; cout<<"Menu:A(dd) D(elete) S(ort) Q(uit),Select one:"< >a; while(a) { if(a=='A') cout<<"数据已经增加"< >a; } return 0; }
2-28
实现一个简单的菜单程序,运行时显示“Menu:A(dd) D(elete) S(ort) Q(uit),Selete one:”提示用户输入。A表示增加,D表示删除,S表示排序,Q表示退出。输入为A、D、S时分别提示“数据已经增加、删除、排序。”,输入Q时程序结束。 (1)if...else...语句,break,continue控制
if else语句
#include
using namespace std;
int main()
{ char a;
cout<<"Menu:A(dd) D(elete) S(ort) Q(uit),Select one:"< cin>>a;
while(a)
{
if(a=='A')
cout<<"Data has added"< else if(a=='D')
cout<<"Data has deleted"< else if(a=='S')
cout<<"Data has sorted"< else if(a=='Q')
break;
else
cout<<"error"<
cin>>a;
}
return 0;
}
using namespace std;
int main()
{ char a;
cout<<"Menu:A(dd) D(elete) S(ort) Q(uit),Select one:"<
while(a)
{
if(a=='A')
cout<<"Data has added"<
cout<<"Data has deleted"<
cout<<"Data has sorted"<
break;
else
cout<<"error"<
cin>>a;
}
return 0;
}
switch语句
#includeusing namespace std; int main() { char a; while(true) {cout<<"Menu:A(dd)D(elete)S(ort)Q(uit),Select one:"<<endl; cin>>a; switch (a) {case 'A':{cout<<"data has added"< continue;} case 'D':{cout<<"data has deleted"< continue;} case 'S':{cout<<"data has sorted"< continue;} case 'Q':break; default:{cout<<"error"< continue;} } break; } return 0; }
2-29
用穷举法找出1~100间的质数并显示出来。
while语句
#include#include using namespace std; int main() {int i=2,j,n=0; while(i<=100) {j=2; while(j<=sqrt(i)) {if(i%j==0) break; j++; } if(j>=sqrt(i)) {cout<"\t"; n++; } if(n%5==0&&n!=0) {n=0; cout<<endl; } i++; } return 0; }
do...while语句
#include#include using namespace std; int main() {int i=2,j,n=0; do{j=2; do{if(i%j==0) break; j++; }while(j<=sqrt(i)); if(j>=sqrt(i)) {cout<"\t"; n++; } if(n%5==0&&n!=0) {n=0; cout<<endl; } i++; }while(i<=99); return 0; }
for语句
#include#include using namespace std; int main() {int i,j,n=0; for(i=2;i<=100;i++) {j=2; for(j=2;j<=sqrt(i);j++) {if(i%j==0) break; } if(j>=sqrt(i)) {cout<"\t"; n++; } if(n%5==0&&n!=0) {n=0; cout<<endl; } } return 0; }
2-32
在程序中定义一个整型变量,赋以1~100的值,要求用户猜这个数,比较两个数的大小,把结果提示给用户,直到猜对为止。
while语句
#include#include #include using namespace std; int main() {int a,b; srand(time(0)); a=rand()%100; cin>>b; while (true) {if (a<b) {cout<<"smaller than the number:"<<endl; cin>>b; } else if (a>b) {cout<<"bigger than the number"<<endl; cin>>b; } else {cout<<"Bingo!"<<endl; break; } } return 0; }
do...while语句
#include#include #include using namespace std; int main() {int a,b; srand(time(0)); a=rand()%100; cin>>b; do {if (a<b) {cout<<"smaller than the number:"<<endl; cin>>b; } else if (a>b) {cout<<"bigger than the number:"<<endl; cin>>b; } else {cout<<"Bingo!"<<endl; break; } }while (true); return 0; }
2-34
口袋中有红黄蓝白黑5种颜色的球若干个。没词葱口袋中取出3个颜色不同的球,问有多少种取法
#includeusing namespace std; int main() {int i,j,k,t=0; cout<<"Red:0,Yellow:1,Blue:2;White:3,Black:4"<<endl; for(i=0;i<=4;i++) {for(j=i+1;j<=4;j++) {if(j==i)continue; for(k=j+1;k<=4;k++) {if(k==i||k==j) continue; cout<endl; t++; } } } cout<<"total:"< endl; return 0; }