//below shows how to output
cout << "hello\n";
/*
This is written by Ernest
and he is super hansome
*//*
if ( conditions )
statement;
*/
if(a >= 60)
cout << "Passed" << "\n";
= 是 assignment operator,用來賦值
a = 5
== 是 comparison operator,用來比較
(a == 5)
常見錯誤: 搞混 = 和 ==
if (grade >= 60)
cout <<"Passed\n";
else
cout <<"Failed\n";if(a >= 90)
cout << "A\n";
else
if(a >= 80)
cout << "B\n";
else
if(a >= 70)
cout << "C\n";
else
cout <"F\n";if(a >= 90)
cout << "A\n";
else if(a >= 80)
cout << "B\n";
else if(a >= 70)
cout << "C\n";
else
cout <"F\n";if(x > 5)
if(y > 5)
cout << "x and y are > 5\n";
else
cout << "x is <= 5";
if(x > 5)
{
if(y > 5)
cout << "x and y are > 5\n";
}
else
cout << "x is <= 5";
通常一行才不加{ }
#include <iostream>
using namespace std;
int main() {
int choice;
cout << "Pick chest 1 or 2: ";
cin >> choice;
if (choice == 1) {
cout << "You found a magic ring!\n";
} else {
cout << "A monster jumps out!\n";
}
return 0;
}
邏輯運算子、運算邏輯
最常見的: and, or, not
if(x > 3 && x < 7) //and
cout << "3 < x < 7\n";Remark:
通常Variable擺在左邊,value 擺在左邊
if(3 < x && x < 7) //and 錯誤版
cout << "3 < x < 7\n";bool a = true;
bool b = false;
int x = 3;
bool c = (x > 3);
bool 可以表示true, false
在數字中 通常 1 代表true,0代表false
Remark: 只要 a 不是 0,if就會執行
int a;
cin >> a;
if(a)
cout << a <<"\n";And(&&): 兩邊都要是true才會成立
Or(||):其中一個條件是true就會成立
Not(!):會把false變成true,true變成false
string today;
cin >> today;
if (today == "Saturday" || today == "Sunday") {
cout << "No school today! (" << today << ")\n";
} else {
cout << "Go to school. (" << today << ")\n";
}#include <iostream>
using namespace std;
int main() {
bool raining = false;
bool sportClass = true;
if (!raining && sportClass) {
cout << "Go to PE class\n";
} else {
cout << "No PE class\n";
}
return 0;
}
zerojudge: d065. 三人行必有我師 (1 行版)
zerojudge: e835. p2.表演座位 (Seats)
補充: 三元運算子
/*Syntax
conditions ? true statement : false statement
*/
int a = 65;
string result = (a >= 60) ? "Passed" : "Fail";
cout << result << endl;
cout << (a >= 60) ? "Passed\n" : "Fail\n";一行版本的if else
int day = 4; // 1=Monday, …, 7=Sunday
switch (day) {
case 1: {
cout << "Monday\n";
break;
}
case 2: {
cout << "Tuesday\n";
break;
}
/*中間省略*/
case 7: {
cout << "Sunday\n";
break;
}
default: {
cout << "Invalid day\n";
break;
}
}
Note:沒有break會繼續往下執行
Truth table