一、函數(function)
把某些特定的處理整合起來,便可隨時呼叫使用,而不需要每次使用都重新寫程式碼。
使用函數的步驟:定義函數-->呼叫函數
範例:
#include<iostream>
using namespace std;
void buy_car(){ //定義買車函數
cout<<"買了一台車子\n";
}
void buy_TV(){ //定義買電視函數
cout<<"買了一台電視\n";
}
int main(){
buy_car(); //呼叫函數
buy_TV();
buy_car();
}
二、參數:將參數傳到函數內處理
將上述範例改為有參數的版本
#include<iostream>
using namespace std;
void buy_car(int x){
cout<<"買了"<<x<<"台車子\n";
}
void buy_TV(int x){
cout<<"買了"<<x<<"台電視\n";
}
int main(){
buy_car(2);
buy_TV(5);
}
三、作業:利用函數寫一個計算最大公因數的程式
無函數寫法
#include<iostream>
using namespace std;
int main(){
int A,B,C;
cout<<"請輸入一個整數A:";
cin>>A;
if(A==0){
cout<<"BYE";
}else{
cout<<"請輸入一個整數B:";
cin >> B;
while ( B!= 0){
C=A%B;
A=B;
B=C;
}
cout <<"最大公因數為:"<<A<< endl;
}
}
請改寫成下列結構
#include<iostream>
using namespace std;
void HCF(int x,int y){
//以下填入HCF找最大公因數的過程
cout <<"最大公因數為:"<<_____<< endl;
}
int main(){
int A,B;
cout<<"請輸入一個整數A:";
cin>>A;
if(A==0){
cout<<"BYE";
}else{
cout<<"請輸入一個整數B:";
cin >> B;
if(B!=0) HCF(A,B);
}
system("PAUSE");
}