实验一
书P63
2-28
(1)
#include<iostream> using namespace std; int main(){ char select; while(1) {cout<<"Menu:A(dd) D(elete) S(ort) Q(uit),Select one:"; cin>>select; if(select=='A') {cout<<"Data has added"<<endl; continue;} else if(select=='D') {cout<<"Data has deleted"<<endl; continue;} else if(select=='S') {cout<<"Data has sorted"<<endl; continue;} else if(select=='Q') break; else cout<<"no such choice,please select again"<<endl; } return 0; }
(2)
#include<iostream> using namespace std; int main() {char select; int i=1; while(i) {cout<<"Menu:A(dd) D(elete) S(ort) Q(uit),Select one:"; cin>>select; if(select=='A'||select=='D'||select=='S'||select=='Q') {switch(select) {case 'A':cout<<"Data has added"<<endl; break; case 'D':cout<<"Data has deleted"<<endl; break; case 'S':cout<<"Data has sorted"<<endl; break; case 'Q':i=0; break; } } else cout<<"no such choice,please select again"<<endl; } return 0; }
2-29
(1)while
#include<iostream> using namespace std; int main() {int n=2,i,flag; while(n<100) {i=2;flag=1; while(i<n) {if(n%i==0) {flag=0; break; } i++; } if(flag==1) cout<<n<<endl; n++; } return 0; }
(2)do while
#include<iostream> using namespace std; int main() {int n=2,i,flag; do{ i=2;flag=1; do{ if(n%i==0) {flag=0; break; } i++; }while(i<n); if(flag==1) cout<<n<<endl; n++; } while(n<100); return 0; }
(3)for
#include<iostream> #include<cmath> using namespace std; int main() {int i,n,flag; for(i=2;i<=100;i++) {flag=1; for(n=2;n<=sqrt(i);n++) if(i%n==0) {flag=0; break;} if(flag==1) cout<<i<<endl; } return 0; }
2-32
(1)do while
#include <cstdlib> #include <iostream> #include <ctime> using namespace std; int main() {srand(time(0)); int n,number; number=rand()%100+1; do {cout<<"guess a number(1-100):"; cin>>n; if(n>100) {cout<<"error"; continue; } if(n<number) cout<<"The number is bigger than yours"<<endl; else if(n>number) cout<<"The nmuber is smaller than yours"<<endl; }while(n!=number); cout<<"congratulations!"; return 0; }
(2)while
#include <cstdlib> #include <iostream> #include <ctime> using namespace std; int main() {srand(time(0)); int n,number; number=rand()%100+1; while(1) {cout<<"guess a number(1-100):"; cin>>n; if(n>100) {cout<<"error"; continue; } if(n==number) {cout<<"congratulations!"; break; } else if(n<number) cout<<"The number is bigger than yours"<<endl; else if(n>number) cout<<"The nmuber is smaller than yours"<<endl; } return 0; }
2-34
#include<iostream> using namespace std; void f(int x) {switch(x) {case 1:cout<<" red"; break; case 2:cout<<" yellow"; break; case 3:cout<<" blue"; break; case 4:cout<<" white"; break; case 5:cout<<" black"; break; } } int main() {int i,j,k,n=1; for(i=1;i<=5;i++) for(j=1;j<=5;j++) for(k=1;k<=5;k++) if(i!=j&&i!=k&&j!=k) {cout<<n; f(i); f(j); f(k); cout<<endl; n++; } return 0; }
实验总结:
①运行2-28时,输入某些标点,程序会出错。
②这四个程序和c语言程序差不多。输入输出语句不同。一些函数的头文件不一样,rand和srand函数不会用,通过老师给的网址查询一下就行了。
互评:
https://www.cnblogs.com/sqcmxg/
https://www.cnblogs.com/jzgjzg/
https://www.cnblogs.com/21savage-code/