C++2 if-else

Comment

//below shows how to output
cout << "hello\n";
/* 
This is written by Ernest
and he is super hansome
*/

If-statement

/*
if ( conditions )
	statement;
*/
if(a >= 60)
	cout << "Passed" << "\n";
	

Comparison Operators

== != =

= 是 assignment operator,用來賦值

a = 5

== 是 comparison operator,用來比較

(a == 5)

常見錯誤: 搞混 = 和 ==

else

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";

else if

if(a >= 90)
	cout << "A\n";
else if(a >= 80)
   	cout << "B\n";
else if(a >= 70)
    cout << "C\n";
else 
    cout <"F\n";

x > 5 而且 y > 5

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";

通常一行才不加{ }

Example

#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;
}

練習一下

logical operator

邏輯運算子、運算邏輯

最常見的: 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";

boolean

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";

intro to logic

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;
}

補充: 三元運算子

/*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

Switch

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會繼續往下執行

Not

Truth table

And

Or

Demorgan's rule

例子

  • 例子1
    • 我不會同時上班和去健身房
    • 我不是沒去上班,或是沒去健身房
  • 例子2
    • 我今天不會去(看電影或吃火鍋)
    • 我今天既不看電影也不吃火鍋
Made with Slides.com