函式實作示例

輸出入小技巧

C格式輸出入

scanf():C語言的輸入指令。
printf():C語言的輸出指令。

e.g. 輸入一日期、輸出同一日期。輸出入日期格式:YYYY/MM/DD

C++ 寫法

#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語言寫法

#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(後面不用加分號)

#define MAXN 100

法二:使用const

const int MAXN = 100;

cout偵錯小技巧:#define一鍵開啟/關閉

開啟:

#define DEBUG // ...前略 #ifdef DEBUG cout << "要輸出檢查的東東" << endl; #endif

關閉:註解掉

#define DEBUG

這一行即可。

e.g.

ab遞迴版,嘗試輸出ab值,觀察segmentation fault的原因

#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)×gcd(a,b)=a×b

翻譯:兩數最小公倍數 x 兩數最大公因數 = 兩數乘積

三數最小公倍數

lcm(a,b,c)=lcm(lcm(a,b),c))

翻譯:

abc 三數的最小公倍數,即為 「
ab
的最小公倍數」 和
c
的最小公倍數。

(懶得補證明請看維基百科

最大公因數的求法

輾轉相除法

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

遞迴法
以下示範遞迴版本的gcd()函式:

int gcd(int a, int b){ // 當遞迴計算直到 b 等於 0 ,則 a 就是兩數最大公因數 if(b == 0) return b // 否則,a, b的最大公因數即為 (b, a%b) 的最大公因數,遞迴計算 return gcd(b, a%b); }