c++实验1
2-28
1 #include<iostream> 2 #include<stdlib.h> 3 using namespace std; 4 int main(){ 5 char a; 6 while(true){ 7 cout<<"Menu:A(dd) D(elet) S(ort) Q(uit),Select one:"; 8 cin>>a; 9 if(a=='A'||a=='D'||a=='S'){ 10 switch(a){ 11 case 'A':cout<< "data has been added"<<endl;break; 12 case 'D':cout<< "data has been deleted"<<endl;break; 13 case 'S':cout<< "data has been sorted"<<endl;break; 14 } 15 } 16 else if(a=='Q') break; 17 else cout<< "no such choice"<<endl; 18 } 19 exit(0); 20 return 0; 21 }
1 #include<iostream> 2 #include<stdlib.h> 3 using namespace std; 4 int main(){ 5 char a; 6 while(true){ 7 cout<<"Menu:A(dd) D(elet) S(ort) Q(uit),Select one:"; 8 cin>>a; 9 if(a=='A') 10 cout<< "data has been added"<<endl; 11 else if(a=='D') 12 cout<< "data has been deleted"<<endl; 13 else if(a=='S') 14 cout<< "data has been sorted"<<endl; 15 else if(a=='Q') 16 break; 17 else 18 cout<< "no such choice"<<endl; 19 } 20 exit(0); 21 return 0; 22 }
2-29
1 #include<iostream> 2 #include<iomanip> 3 using namespace std; 4 int main(){ 5 int i,j,k=0; 6 for(i=2;i<=100;i++){ 7 int m=0; 8 for(j=2;j<i;j++) 9 if(i%j==0)m++; 10 if(m==0){ 11 cout<<setw(6)<<i; 12 k++; 13 } 14 if(k==4){ 15 k=0; 16 cout<<endl; 17 } 18 } 19 20 return 0; 21 }
2-32
1 #include<iostream> 2 using namespace std; 3 int main(){ 4 int num=78; 5 cout<<"choose one number between 1 and 100"<<endl; 6 while(true){ 7 int gesn; 8 cin>>gesn; 9 if(gesn==num){ 10 cout<<"you got it,congratulations!"<<endl;break; 11 } 12 else if(gesn>num) 13 cout<<"this number is too big,pls try again"<<endl; 14 else if(gesn<num) 15 cout<<"this number is too small,pls try again"<<endl; 16 } 17 return 0; 18 }
2-34
无顺序:
1 #include<iostream> 2 using namespace std; 3 int combine(int,int); 4 int main(){ 5 cout<<"有"<<combine(3,5)<<"种取法"<<endl; 6 return 0; 7 } 8 int combine(int x,int y){ 9 int i,j=1; 10 for(i=1;i<=y;i++) 11 j*=i; 12 for(i=1;i<=x;i++) 13 j/=i; 14 for(i=1;i<=y-x;i++) 15 j/=i; 16 return j; 17 }
有顺序:
1 #include<iostream> 2 #include<string.h> 3 #include<iomanip> 4 using namespace std; 5 int main(){ 6 char a[5][10]; 7 strcpy(a[0],"red"); 8 strcpy(a[1],"yellow"); 9 strcpy(a[2],"blue"); 10 strcpy(a[3],"white"); 11 strcpy(a[4],"black"); 12 int i,j,k,num=0; 13 for(i=0;i<5;i++){ 14 for(j=0;j<5;j++){ 15 if(j==i) 16 continue; 17 for(k=0;k<5;k++){ 18 if(k==i||k==j) 19 continue; 20 cout<<setw(7)<<a[i]; 21 cout<<setw(7)<<a[j]; 22 cout<<setw(7)<<a[k]<<endl; 23 num++; 24 } 25 } 26 } 27 cout<<num<<endl; 28 return 0; 29 30 }
第二章知识框架
实践中的问题:
1. 在实验2-28中发现:如果输入两个字母的指令会输出两次,还没有搞清楚原因是什么。觉得应该是依次只能输入一个指令,就相当于输入了两次。
2. 第一次写2-29用stew控制cout输出长度时没有包含<iomanip>,导致编译出错了。
3. 2-34第二种方法感觉基本上是用的c中用的方法。