C/C++ 教學系列(一):Hello World 程式教學 —— 從零開始學 C/C++,寫出你的第一個程式! 1. 什麼是 Hello World? 「Hello World」是程式設計的經典入門範例,用於驗證開發環境是否正確配置,並幫助初學者理解最基本的程式結構。 2. 開發環境準備 在開始寫程式之前,你需要一個編譯器(Compiler)和編輯器(Editor)來編寫和執行 C/C++ 程式。 推薦工具 編譯器(將程式碼轉換為可執行檔): GCC (Linux/macOS 預設安裝) MinGW (Windows 推薦) Visual Studio 內建 MSVC (Windows) 編輯器 / IDE(寫程式碼的環境): Visual Studio Code (VS Code) + C/C++ 擴充套件 Dev-C++ (輕量級 IDE) CLion (專業 C/C++ IDE) 3. 第一個 C 語言 Hello World 程式碼 #include <stdio.h> // 引入標準輸入輸出函式庫 int main() { // 主函式,程式從這裡開始執行 printf("Hello, World!\n"); // 輸出字串到螢幕 return 0; // 回傳 0 表示程式正常結束 } 說明 #include <stdio.h> 引入標準輸入輸出函式庫,讓程式可以使用 printf() 等函數。 int main() 主函式,程式執行的入口點。 printf("Hello, World!\n"); 在螢幕上印出 Hello, World!,\n 代表換行。 return 0; 回傳 0 表示程式正常結束。 將程式碼儲存為 hello.c。 開啟終端機(Terminal / CMD),進入檔案所在目錄。 編譯並執行: gcc hello.c -o hello # 編譯 ./hello # 執行 (Linux/macOS) hello.exe # 執行 (Windows) Hello, World! 4. 第一個 C++ 語言 Hello World 5. C++ 是 C 語言的擴展版本,支援物件導向程式設計(OOP)。 程式碼 #include <iostream> // 引入 C++ 標準輸入輸出函式庫 int main() { // 主函式 std::cout << "Hello, World!" << std::endl; // 使用 cout 輸出 return 0; // 回傳 0 表示程式正常結束 } #include <iostream> C++ 的標準輸入輸出函式庫,提供 cout 和 cin。 std::cout cout 用於輸出,<< 是運算子,將資料傳送到輸出流。 std::endl 換行,類似 C 的 \n。 如何執行? 將程式碼儲存為 hello.cpp。 編譯並執行: g++ hello.cpp -o hello # 使用 g++ 編譯 C++ ./hello # 執行 輸出結果與 C 語言相同: Hello, World! 5. 常見問題 FAQ Q1: 為什麼要用 #include? #include 是預處理指令,用來引入函式庫,讓程式可以使用現成的函數(如 printf、cout)。 Q2: int main() 一定要回傳 0 嗎? 在 C/C++ 中,return 0; 表示程式正常結束,非 0 值通常代表錯誤。 在 C++ 中,如果省略 return 0;,編譯器會自動補上(僅限 main() 函數)。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up