if else
if (條件) {
// 條件成立時執行
}
else {
// 上述條件不成立時執行
if (分數 >= 90) {
cout << "A";
}
else if (分數 >= 80) {
cout << "B";
}
else {
cout << "C";
}
ex:
| >= | 大於等於 |
| <= | 小於等於 |
| != | 不相等 |
| == | 相等 |
| || | OR(有一個真就為真) |
| && | AND(兩個都真才為真) |
| ! | NOT(反向) |
for (int i = 1; i <= 100; i++) {
if (i % 7 == 0) {
cout << i;
break; // 找到就結束
}
}
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0)
continue; // 偶數跳過
cout << i << endl;
}
7
1 3 5 7 9
int score = 75;
cout << (score >= 60 ? "及格" : "不及格");
條件式 ? 條件式符合時執行: 條件式不符合時執行7
及格
ex:
while for
次數迴圈
for (int i = 0; i < 5; i++) {
cout << i << endl;
}
條件迴圈
int x = 0;
while (x < 5) {
cout << x << endl;
x++;
}
*條件成立就一直跑
至少跑一次
int x = 0;
do {
cout << x << endl;
x++;
} while (x < 5);
*先執行,再判斷條件
string
char ch='z'; // 存的是 ASCII 122用單引號 ' '
string name = "ZSISC";用雙引號 ""
#include <iostream>
using namespace std;
int main() {
string sentence;
getline(cin, sentence);
string a;
cin >> a;
cout << sentence << a;
}讀整行
遇空白停止
string a = "Hello";
string b = "World";
cout << a + b;
字串相加 HelloWorld
string s = "APPLE";
cout << s[0]; // A
取得字元 A
判斷空字串
string a = " ";
if (a.empty()) cout << "oh";
else cout << "no";string a = "ZSISC";
cout << a.length();
取得字串長度 5