跳轉到內容

程式設計基礎/變數示例 C++

來自華夏公益教科書,開放書籍,開放世界

以下示例演示了 C++ 中的資料型別、算術運算和輸入。

資料型別

[編輯 | 編輯原始碼]
 // This program demonstrates variables, literal constants, and data types.
 
 #include <iostream>
 #include <sstream>
 
 using namespace std;
 
 int main() {
     int i;
     double d;
     string s;
     bool b;
     
     i = 1234567890;
     d = 1.23456789012345;
     s = "string";
     b = true;
     cout << "Integer i = " << i << endl;
     cout << "Double d = " << d << endl;
     cout << "String s = " << s << endl;
     cout << "Boolean b = " << b << endl;
     return 0;
 }
Integer i = 1234567890
Real r = 1.23457
String s = string
Boolean b = 1

每個程式碼元素代表

  • // 開始註釋
  • #include <iostream> 包含標準輸入輸出流//
  • #include <sstream> 包含標準字串流//
  • using namespace std 允許引用 stringcoutendl,而無需編寫 std::stringstd::coutstd::endl
  • int main() 開始主函式,該函式返回一個整數值
  • { 開始程式碼塊
  • int i 定義名為 i 的整型變數
  • ; 結束每行 C++ 程式碼
  • double d 定義名為 d 的雙精度浮點型變數
  • string s 定義名為 s 的字串變數
  • bool b 定義名為 b 的布林變數
  • i = , d = , s =, b = 將字面量值分配給相應的變數
  • cout 是標準輸出
  • << 將下一個元素定向到標準輸出
  • endl 結束當前行
  • return 0 從 main 返回值 0,表示主函式成功完成
  • } 結束程式碼塊
 // This program demonstrates arithmetic operations.
 
 #include <iostream>
 #include <sstream>
 
 using namespace std;
 
 int main() {
     int a;
     int b;
     
     a = 3;
     b = 2;
     
     cout << "a = " << a << endl;
     cout << "b = " << b << endl;
     cout << "a + b = " << a + b << endl;
     cout << "a - b = " << a - b << endl;
     cout << "a * b = " << a * b << endl;
     cout << "a / b = " << a / b << endl;
     cout << "a % b = " << a + b << endl;
     return 0;
 }
a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1
a % b = 5

每個新的程式碼元素代表

  • +, -, *, /, and % 分別代表加法、減法、乘法、除法和模運算。
 // This program converts an input Fahrenheit temperature to Celsius.
 //
 // References:
 // https://www.mathsisfun.com/temperature-conversion.html
 // https://wikibook.tw/wiki/C%2B%2B_Programming
 #include <iostream>
 
 using namespace std;
 
 int main() {
     double fahrenheit;
     double celsius;
     
     cout << "Enter Fahrenheit temperature:" << endl;
     cin >> fahrenheit;
 
     celsius = (fahrenheit - 32) * 5 / 9;
 
     cout << fahrenheit << "° Fahrenheit is " << celsius << "° Celsius" << endl;
 
     return 0;
 }
Enter Fahrenheit temperature:
 100
100° Fahrenheit is 37.7778° Celsius

每個新的程式碼元素代表

  • cin >> fahrenheit 從標準輸入讀取下一個整數並將該值分配給 fahrenheit 變數

參考文獻

[編輯 | 編輯原始碼]
華夏公益教科書