#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<iostream> using namespace std; int main() { char a; cout<<"Menu:A(dd) D(elete) S(ort) Q(uit),Select one:"<<endl; cin>>a; while(a) { if(a=='A') cout<<"Data has added"<<endl; else if(a=='D') cout<<"Data has deleted"<<endl; else if(a=='S') cout<<"Data has sorted"<<endl; else if(a=='Q') break; else cout<<"error"<<endl; 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:"< >a; switch (a) { case 'A':{cout<<"data has added"<
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<
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<
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<
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; } else if (a>b) {cout<<"bigger than the number"< >b; } else {cout<<"Bingo!"<
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; } else if (a>b) {cout<<"bigger than the number:"< >b; } else {cout<<"Bingo!"<
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"<