條件假設

if else

if (條件) {
   // 條件成立時執行
} 
else {
    // 上述條件不成立時執行

條件判斷

if (分數 >= 90) {
    cout << "A";
} 
else if (分數 >= 80) {
    cout << "B";
} 
else {
    cout << "C";
}

ex:

邏輯運算子

>= 大於等於
<= 小於等於
!= 不相等
== 相等
|| OR(有一個真就為真)
&& AND(兩個都真才為真)
! NOT(反向)

比較運算子

continue:跳過這回合

break:中途結束流程

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 迴圈

次數迴圈

for (int i = 0; i < 5; i++) {
    cout << i << endl; 
}

while 迴圈

條件迴圈

int x = 0;
while (x < 5) {
    cout << x << endl;
    x++;
}

*條件成立就一直跑

do-while 迴圈

至少跑一次

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

review

By shiny0515