實驗結論ios
P63 2-28c++
(1)If..else.. 進行判斷,break continue控制程序流程函數
#include<iostream>ui
using namespace std;spa
int main(){3d
char choice;blog
while(1){ci
cout<<"Menu:A(dd) D(elete) S(ort) Q(uit),Select one:";it
cin>>choice;io
if(choice=='A'||choice=='a') cout<<"Dates have been added"<<endl;
else if(choice=='D'||choice=='d') cout<<"Dates have been deleted"<<endl;
else if(choice=='S'||choice=='s') cout<<"Dates have been sorted"<<endl;
else if(choice=='Q'||choice=='q') break;
else cout<<"no such choice"<<endl;
}
return 0;
}
(2)switch循環語句
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
char choice;
while(1){
cout<<"Menu:A(dd) D(elete) S(ort) Q(uit),Select one:";
cin>>choice;
switch(choice){
case 'A':
cout<<"Dates have been added"<<endl;
break;
case 'D':
cout<<"Dates have been deleted"<<endl;
break;
case 'S':
cout<<"Dates have been sorted"<<endl;
break;
case 'Q': exit(0);
default: cout<<"no such choice"<<endl; break;
}
}
return 0;
}
P63 2-291窮舉法找質數
(1)for循環
#include<iostream>
#include<cmath>
using namespace std;
int main(){
int i,m,n,t=1;
for(i=1;i<=100;i++)
{
t=1;
if(i==1) continue;//將1單獨分離,不知道是否有通法。
else if(i==2)
cout<<i<<" ";
else
{
m=sqrt(i);
for(n=2;n<=m;n++)
{
if(i%n==0) t=0;
}
if(t==1) cout<<i<<" ";
}
}
return 0;
}
(2)do..while 循環
#include<iostream>
#include<cmath>
using namespace std;
int main(){
int a=1,m,i;
bool t; //嘗試使用了布爾型,雖然不必。
do{
i=2;
m=sqrt(a);
if(a==1) {
t=false;
}
else
{
do{
if(a%i==0)
{
t=false;
break;
}
i++;
}while(i<=m);
if(i>m) t=true;
}
if(t==true)
cout<<a<<" ";
a++;
}while(a<=100);
return 0;
}
(3)while循環
#include<iostream>
#include<cmath>
using namespace std;
int main(){
int i,a=1,m;
while(a<=100)
{
i=2;
if(a==1) {a++;continue;}
m=sqrt(a);
while(i<=m)
{
if(a%i==0) break;
i++;
}
if(i>m) cout<<a<<" ";
a++;
}
return 0;
}
P63 2-32
(1)數字固定
#include<iostream>
using namespace std;
int main(){
int i,n;
n=40;
cout<<"Please guess the number(1~100)"<<endl;
while(1) //同窗介紹的屢次輸入的方式,還有其餘方法嗎?
{
cin>>i;
if(i>40&&i<=100) cout<<"bigger than the number"<<endl;
else if(i<40&&i>=0) cout<<"lower than the number"<<endl;
else if(i==n) break;
else cout<<"out of range"<<endl;
}
cout<<"gradulation!you are right!"<<endl;
return 0;
}
(2)數字隨機
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
int rnum,i;
srand(time(NULL)); //嘗試使用了隨機種子。
rnum=rand()%(100)+1;
while(1)
{
cin>>i;
if(i>rnum&&i<=100) cout<<"bigger than the number"<<endl;
else if(i<rnum&&i>=0) cout<<"lower than the number"<<endl;
else if(i==rnum) break;
else cout<<"out of range"<<endl;
}
cout<<"gradulation!you are right!"<<endl;
return 0;
}
組合數
P63 2-34
#include<iostream>
using namespace std;
int comp(int n,int k) //組合數函數
{
if(k>n) return 0;
else if(k==n||k==0) return 1;
else return (comp(n-1,k-1)+comp(n-1,k));
}
int main(){
int n,k,num;
cin>>n>>k;
num=comp(n,k);
cout<<num<<endl;
return 0;
}
實驗總結與體會
1.常用for循環致使do..while..和while兩種循環不是很熟練。
2srand的隨機種子十分有趣,對抽取隨機編號程序十分有效。
3對程序排版仍是不是很熟練,有的時候會顯得很亂。
4c++的代碼形式相對於c十分的簡練有效,特別是函數的時候,能系統自主選擇最合適的方案這個設定頗有趣