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;
}
以整數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. a
、b
值,觀察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;
}ㄑ
兩數最小公倍數
翻譯:兩數最小公倍數 x 兩數最大公因數 = 兩數乘積
三數最小公倍數
翻譯:
(懶得補證明…請看維基百科)
輾轉相除法
Learn More →
Learn More →
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);
}
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up