程式設計基礎/變數示例 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允許引用string、cout和endl,而無需編寫std::string、std::cout和std::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 變數