【C++入門】(一)C++入門
阿新 • • 發佈:2022-12-02
一. 編寫一個簡單的C++程式——手速練習
#include <iostream> using namespace std; int main() { cout << "Hello World" << endl; return 0; }
二. 語法基礎
1. 變數的定義
- 變數必須先定義,才可以使用
- 不能重名
#include <iostream> using namespace std; int main() { int a = 5; int b, c = a, d = 10 / 2; return0; }
2. 常用變數型別及範圍:
3. 輸入輸出:
//整數的輸入輸出: #include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; cout << a + b << endl; return 0; }
//字串的輸入輸出: #include <iostream> #include <string> using namespace std; int main() {string str; cin >> str; cout << str; return 0; }
//輸入輸出多個不同型別的變數: #include <iostream> #include <string> using namespace std; int main() { int a, b; string str; cin >> a; cin >> b >> str; cout << str << " !!! " << a + b << endl;return 0; }
4. 表示式
//整數的加減乘除四則運算: #include <iostream> #include <string> using namespace std; int main() { int a = 6 + 3 * 4 / 2 - 2; cout << a << endl; int b = a * 10 + 5 / 2; cout << b << endl; cout << 23 * 56 - 78 / 3 << endl; return 0; }
//浮點數(小數)的運算: #include <iostream> #include <string> using namespace std; int main() { float x = 1.5, y = 3.2; cout << x * y << ' ' << x + y << endl; cout << x - y << ' ' << x / y << endl; return 0; }
//整型變數的自增、自減: #include <iostream> #include <string> using namespace std; int main() { int a = 1; int b = a ++ ; cout << a << ' ' << b << endl; int c = ++ a; cout << a << ' ' << c << endl; return 0; }
//變數的型別轉換: #include <iostream> #include <string> using namespace std; int main() { float x = 123.12; int y = (int)x; cout << x << ' ' << y << endl; return 0; }