C++與演算法

邏輯運算

邏輯符號對照表

C++ code 中文意思 舊C++ code
and &&
or ||
not 的相反 !



邏輯運算範例 - AND (且)

每一列輸入兩次段考成績,如果兩次都及格,學期成績才會及格。

及格輸出PASS,否則輸出FAIL。

code

#include<iostream>
using namespace std;

int main()
{
    int grade1, grade2;

    while( cin >> grade1 >> grade2 )
    {
        if( grade1>=60 and grade2>=60 )
        {
            cout << "PASS" << endl;
        }
        else
        {
            cout << "FAIL" << endl;
        }
    }

    return 0;
}

input

59 100
61 62
50 30

output

FAIL
PASS
FAIL



邏輯運算範例 - OR (或)

PS4一台要價12980元。小鳴非常想要一台。

小鳴有一張信用卡和一些現金。

不過買東西時,只能選擇一種付款方式,沒辦法混合使用。


每一列輸入 信用卡餘額 及 現金 ,其中一個大於等於12980即可購買PS4。

購買時輸出PS4,否則輸出QQ

code

#include<iostream>
using namespace std;

int main()
{
    int credit, money;

    while( cin >> credit >> money )
    {
        if( credit>=12980 or money>=12980 )
        {
            cout << "PS4" << endl;
        }
        else
        {
            cout << "QQ" << endl;
        }
    }

    return 0;
}

input

15000 100
12000 12000
50000 20000

output

PS4
QQ
PS4



邏輯運算範例 - NOT (的相反)

東方人認為數字4不吉利。

西方人認為數字13不吉利。

請寫一個程式輸入一些數字,判斷這些數字吉不吉利。

如果數字不是4也不是13,就輸出good,否則輸出bad

小技巧

能夠用小括號( )決定運算的先後順序。

code

#include<iostream>
using namespace std;

int main()
{
    int num;

    while( cin >> num )
    {
        if( not( num==4 or num==13 ) )   // <----here
        {
            cout << "good" << endl;
        }
        else
        {
            cout << "bad" << endl;
        }
    }

    return 0;
}

input

4
7
13
18

output

bad
good
bad
good