// program_1_1.cpp
#include // 標準輸入輸出串流
int main() { // 程式入口,返回 int
std::cout << "Let's learn to write a C++ Program."; // 輸出到標準輸出
std::cin.get(); // 等待按鍵,防止控制台瞬間關閉
return 0; // 返回 0 表示成功
}
關鍵點:`#include
// program_1_2.cpp : 求兩數之和
#include
int main() {
int a = 43, b = 37, sum = a + b;
std::cout << "The sum is " << sum << std::endl;
std::cin.get(); return 0;
}
// program_1_3.cpp : 圓面積 (常數、浮點數、鍵盤輸入)
#include
int main() {
const float PI = 3.14f; // 常數,編譯期決定,不可修改
float radius;
std::cout << "Enter radius: ";
std::cin >> radius; // 從標準輸入讀取到 radius
float area = PI * radius * radius;
std::cout << "\nThe area of circle is: " << area << std::endl;
std::cin.get(); return 0;
}
// program_1_4.cpp : 攝氏/華氏互轉
#include
int main() {
float t; char type;
const float FACTOR = 1.8f, OFFSET = 32.0f;
std::cout << "Enter temperature: "; std::cin >> t;
std::cout << "C or F? "; std::cin >> type;
if (type == 'c' || type == 'C') {
std::cout << "Fahrenheit = " << t * FACTOR + OFFSET << std::endl;
} else if (type == 'f' || type == 'F') {
std::cout << "Celsius = " << (t - OFFSET) / FACTOR << std::endl;
} else {
std::cout << "Invalid type." << std::endl;
}
std::cin.get(); return 0;
}
// program_1_5.cpp : 四則運算,直到輸入 'n' 退出
#include
int main() {
int x, y; char op, cont = 'y';
while (cont != 'n' && cont != 'N') {
std::cout << "First integer: "; std::cin >> x;
std::cout << "Second integer: "; std::cin >> y;
std::cout << "Operator (+ - * /): "; std::cin >> op;
switch (op) {
case '+': std::cout << x << " + " << y << " = " << x + y; break;
case '-': std::cout << x << " - " << y << " = " << x - y; break;
case '*': std::cout << x << " * " << y << " = " << x * y; break;
case '/':
if (y != 0) std::cout << x << " / " << y << " = " << x / y;
else std::cout << "Divide by zero!";
break;
default: std::cout << "Invalid operator!";
}
std::cout << "\nContinue? (y/n): "; std::cin >> cont;
}
std::cin.get(); return 0;
}
關鍵點:`while` 迴圈條件控制流程、`switch` 多分支、`cin` 讀取字元會跳過空白 (含換行),若需讀取空白需用 `cin.get()` 或 `getline`。
| 錯誤代碼 | 現象 | 原因 | 修正 |
|---|---|---|---|
| `void main()` | 編譯警告/錯誤 | 標準要求 `int main()` | 改為 `int main()` 並 `return 0;` |
| 缺 `#include | `cout`/`cin` 未宣告 | 未引入串流庫 | 加上頭檔 |
| `std::cin >> ch` 讀不到字元 | 跳過輸入 | 緩衝區殘留換行符 | 前置 `std::cin.ignore()` 或用 `std::getline` |
| 整數除法截斷 | `5/2 == 2` | 整數型別除法向零截斷 | 至少一邊轉 `float`/`double` |
| 迴圈無法退出 | 死迴圈 | 條件變數未在迴圈內更新 | 檢查 `cont` 是否正確讀取並更新 |
這五個範例涵蓋 C++ 核心基礎:主函數、輸入輸出、變數與型別、常數、運算子、條件、迴圈、錯誤處理。建議逐行手敲、編譯、運行、修改、觀察差異——「手感」是程式設計入門最寶貴的資產。