一、函數(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:";
while (cin >> A){
if(A==0){
cout<<"BYE";
break;
}else{
cout<<"請輸入一個整數B:";
cin >> B;
while ( B!= 0){
C=A%B;
A=B;
B=C;
}
cout <<"最大公因數為:"<<A<< endl;
}
cout<<"---------------\n請輸入一個整數A:";
}
}
2.使用函數的版本b
#include<iostream>
using namespace std;
void gcd(int A , int B ); //宣告
int main(){
int x,y;
cout<<"請輸入一個整數x:";
while (cin >> x){
if(x==0){
cout<<"BYE"<<endl;
break;
}else{
cout<<"請輸入一個整數y:";
cin >> y;
gcd(x,y);
}
cout<<"---------------\n請輸入一個整數x:";
}
}
void gcd(int A , int B){
int C;
while ( B!= 0){
C=A%B;
A=B;
B=C;
}
cout <<"最大公因數為:"<<A<< endl;
}
四、傳回值
將上述最大公因數的函數找出之數值傳回呼叫處
#include<iostream>
using namespace std;
int gcd(int x , int y); //宣告
int main(){
int x,y,z;
cout<<"請輸入一個整數x:";
while (cin >> x){
if(x==0){
cout<<"BYE"<<endl;
break;
}else{
cout<<"請輸入一個整數y:";
cin >> y;
z=gcd(x,y);
cout<<"最大公因數為"<<z<<endl;
}
cout<<"---------------\n請輸入一個整數x:";
}
}
int gcd(int A , int B){
int C;
while ( B!= 0){
C=A%B;
A=B;
B=C;
}
return A;
}
作業:
請使用函數寫法完成以下程式
(1)輸入兩個整數,計算兩數間的所有整數和
本題函數宣告為 int sumXY(int x,int y);
(2)輸入一個整數,計算此數的三次方
本題函數宣告為 int cube(int x);
執行結果如下圖
注意:以上兩小題請寫在一個程式檔案內。