# 函式實作示例
## 輸出入小技巧
### C格式輸出入
**`scanf()`**:C語言的輸入指令。
**`printf()`**:C語言的輸出指令。
e.g. 輸入一日期、輸出同一日期。輸出入日期格式:`YYYY/MM/DD`
**C++ 寫法**
```cpp=
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int y, m, d;
char c;
cin >> y >> c >> m >> c >> d;
cout << setfill('0') << setw(4) << y << "/"
<< setfill('0') << setw(2) << m << "/"
<< setfill('0') << setw(2) << d << "\n";
return 0;
}
```
**C語言寫法**
```c=
#include <stdio.h>
int main(){
int y, m, d;
scanf("%d/%d/%d", &y, &m, &d);
printf("%04d/%02d/%02d\n", y, m, d);
return 0;
}
```
## 避免VLA的陣列宣告方式
以整數`MAXN`宣告為例,假設題目給定最大值為`100`,在`main`函式之前:
**法一:使用`#define`**(後面不用加分號)
```cpp=
#define MAXN 100
```
**法二:使用`const`**
```cpp=
const int MAXN = 100;
```
## `cout`偵錯小技巧:`#define`一鍵開啟/關閉
開啟:
```cpp=
#define DEBUG
// ...前略
#ifdef DEBUG
cout << "要輸出檢查的東東" << endl;
#endif
```
關閉:註解掉
```cpp=
#define DEBUG
```
這一行即可。
e.g. $a^b$--遞迴版,嘗試輸出`a`、`b`值,觀察`segmentation fault`的原因
```cpp=
#include <iostream>
#define DEBUG
using namespace std;
int p(int a, int b){
#ifdef DEBUG
cout << a << " " << b << endl;
#endif
return a * p(a, b-1);
}
int main(){
int a, b;
cin >> a >> b;
cout << p(a, b) << endl;
return 0;
}ㄑ
```
## 「一起回家的日子」解題示例
### 最小公倍數的求法
**兩數最小公倍數**
> $lcm(a, b) \times gcd(a, b) = a \times b$
翻譯:兩數最小公倍數 x 兩數最大公因數 = 兩數乘積
**三數最小公倍數**
> $lcm(a, b, c) = lcm(lcm(a, b), c))$
翻譯:$a、b、c$ 三數的最小公倍數,即為 「$a、b$ 的最小公倍數」 和 $c$ 的最小公倍數。
(懶得補證明...請看[維基百科](https://zh.wikipedia.org/zh-tw/%E6%9C%80%E5%B0%8F%E5%85%AC%E5%80%8D%E6%95%B8))
### 最大公因數的求法
**輾轉相除法**
- 原理:請自行參考網路資料,e.g. [使用方法](https://www.liveism.com/live-concept.php?q=%E6%9C%80%E5%A4%A7%E5%85%AC%E5%9B%A0%E6%95%B8%E7%9A%84%E6%B1%82%E6%B3%95%E2%94%80%E8%BC%BE%E8%BD%89%E7%9B%B8%E9%99%A4%E6%B3%95)、[原理說明](http://www.mathland.idv.tw/fun/euclidean.htm)、[影片講解](https://www.youtube.com/watch?v=fGesPF3QA1U)、[維基百科](https://zh.wikipedia.org/zh-tw/%E8%BC%BE%E8%BD%89%E7%9B%B8%E9%99%A4%E6%B3%95)。
- 程式:以下示範迴圈法,輸入兩個數字,透過輾轉相除法,可輸出最大公因數。



**遞迴法**
以下示範遞迴版本的`gcd()`函式:
```cpp=
int gcd(int a, int b){
// 當遞迴計算直到 b 等於 0 ,則 a 就是兩數最大公因數
if(b == 0)
return b
// 否則,a, b的最大公因數即為 (b, a%b) 的最大公因數,遞迴計算
return gcd(b, a%b);
}
```