C++與演算法

巢狀 if

巢狀指的是像鳥巢一般,一層包一層包下去…

在這裡是指if裡面還有if的情況。


範例 - 我能結婚嗎?

我國民法在民國100年以前,規定男女結婚最低限度的年齡則分別為 18 歲及 16 歲。讓我們把時光倒回過去,請寫一段程式讓使用者輸入性別和年齡,判斷在修法以前他/她能不能結婚。

輸入說明

第一列:一個整數 1代表男生 、 2代表女生

第二列:一個整數代表年齡

code(一步到位版)

#include<iostream>
using namespace std;

int main()
{
    int sex;
    int age;

    cin >> sex >> age;

    if( sex==1 and age>=18 )
    {
        cout << "You are marriageable." << endl;
    }
    if( sex==1 and age<18 )
    {
        cout << "You are NOT marriageable." << endl;
    }
    if( sex==2 and age>=16 )
    {
        cout << "You are marriageable." << endl;
    }
    if( sex==2 and age<16 )
    {
        cout << "You are NOT marriageable." << endl;
    }

    return 0;
}

code(巢狀版)

#include<iostream>
using namespace std;

int main()
{
    int sex;
    int age;

    cin >> sex >> age;
    if( sex==1 )
    {
        if( age >= 18 )
        {
            cout << "You are marriageable." << endl;
        }
        else
        {
            cout << "You are NOT marriageable." << endl;
        }
    }
    if( sex==2 )
    {
        if( age >= 16 )
        {
            cout << "You are marriageable." << endl;
        }
        else
        {
            cout << "You are NOT marriageable." << endl;
        }
    }

    return 0;
}

input1

1
17

output1

You are NOT marriageable.


input2

2
17

output2

You are marriageable.


自己試試看

  • 一開始不要輸入 12,會發生什麼事?
  • 如何避免以上的情況?