1. 程式人生 > >C++實驗二

C++實驗二

clas ret 如果 c++ OS 語句 esp end pos

1.

(1)

#include<iostream>
using namespace std;
int main()
{
char i;
cout<<"Menu:A(dd) D(elete) S(ort) Q(uit)"<<endl;
while (true)
{
cin>>i;
if(i==‘A‘)
cout<<"數據已經增加"<<endl;
else if(i==‘D‘)
cout<<"數據已經刪除"<<endl;
else if(i==‘S‘)
cout<<"數據已經排序"<<endl;
else if(i==‘Q‘)
break;
}
return 0;
}

技術分享圖片

(2)

#include<iostream>
using namespace std;
int main()
{
char i;
cout<<"Menu:A(dd) D(elete) S(ort) Q(uit)"<<endl;
while (true)
{
cin>>i;
switch(i){
case ‘A‘:
cout<<"數據已經增加"<<endl;continue;
case ‘D‘:
cout<<"數據已經刪除"<<endl;continue;
case ‘S‘:
cout<<"數據已經排序"<<endl;continue;
case ‘Q‘:
break;}
}
return 0;
}

技術分享圖片

2.

(1)

要判斷一個數是否為質數,需要將這個數k與1到根號k之間的整數相除,如果其中沒有數能被整除則k為質數,反之則不是。

(2)

#include<iostream>
#include<cmath>
#include<stdlib.h>
using namespace std;
int main()
{
int k,i;
cout<<"1~100間的質數有"<<endl;
for(k=2;k<=100;k++)
{
for(i=2;i<=sqrt(k);i++)
{
if(k%i==0)
break;
}
if(i>=sqrt(k))
cout<<k<<endl;
}
system("pause");
return 0;
}

技術分享圖片

3.

#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
cout<<"please guess a number between 1 and 100,I will tell you whether it is higher or lower"<<endl;
int x,y;
x=rand()%100;
cin>>y;
while(y!=x){
if(y>x){
cout<<"lower"<<endl;
cin>>y;continue;}

else{
cout<<"higher"<<endl;
cin>>y;continue;}
}
cout<<"yes!"<<endl;
return 0;
}

技術分享圖片

3.

#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
//利用排列組合思想可知為5*4/(2*1),可以理解為在5種顏色中選兩個不拿,先在5個中選一個,再在剩下4個中選1個。
int t,x,y;
for(x=1;x<=5;++x)
for(y=x+1;y<=5;++y)
++t;
cout<<"有"<<t<<"種取法";
return 0;
}

技術分享圖片

總結:

感覺自己學的不是很好,很多都是翻了好幾遍書、想了好久,然後還在同學們的幫助下才完成的,發現有的語句知道卻不明白在如何實際程序中運用,以後還是要多多練習。

C++實驗二