季節判斷

題目說明

題目只有一個值的輸入,要判斷季節是什麼,即一個字串輸出。

第一種解法

這題有非常多種解法,我們這邊先示範最基本的,根據每個條件去做判斷。之前有教過基本運算,大家可以自己思考看看如何透過運算子,讓判斷式縮減到只需要四個。

首先第一步先讀入月份。

cin >> x;

然後根據題目我們可以列出判斷式,如果是一月就輸出春天。

if (x == 1) cout << "spring\n";

接著根據題義寫出其它 11 個月份,就完成了。

if (x == 1) cout << "spring\n";
if (x == 2) cout << "spring\n";
if (x == 3) cout << "spring\n";
if (x == 4) cout << "summer\n";
if (x == 5) cout << "summer\n";
if (x == 6) cout << "summer\n";
if (x == 7) cout << "fall\n";
if (x == 8) cout << "fall\n";
if (x == 9) cout << "fall\n";
if (x == 10) cout << "winter\n";
if (x == 11) cout << "winter\n";
if (x == 12) cout << "winter\n";

最後的程式碼如下:

#include <iostream>
using namespace std;

int x;

int main() {
    cin >> x;
    if (x == 1) cout << "spring\n";
    if (x == 2) cout << "spring\n";
    if (x == 3) cout << "spring\n";
    if (x == 4) cout << "summer\n";
    if (x == 5) cout << "summer\n";
    if (x == 6) cout << "summer\n";
    if (x == 7) cout << "fall\n";
    if (x == 8) cout << "fall\n";
    if (x == 9) cout << "fall\n";
    if (x == 10) cout << "winter\n";
    if (x == 11) cout << "winter\n";
    if (x == 12) cout << "winter\n";
}

第二種解法

是不是覺得上面的程式碼有點冗長?我們可以用之前提到的 switch 來簡化程式碼:

switch (x) {
    case 1:
    case 2:
    case 3:
        cout << "spring\n";
        break;
    case 4:
    case 5:
    case 6:
        cout << "summer\n";
        break;
    case 7:
    case 8:
    case 9:
        cout << "fall\n";
        break;
    case 10:
    case 11:
    case 12:
        cout << "winter\n";
        break;
}

這就充分利用到了 switch「如果沒有 break 就會一直往下執行」的特性,讓我們可以把相同的結果寫在一起,讓程式碼更簡潔。

完整的程式碼如下:

#include <iostream>
using namespace std;

int x;

int main() {
    cin >> x;
    switch (x) {
        case 1:
        case 2:
        case 3:
            cout << "spring\n";
            break;
        case 4:
        case 5:
        case 6:
            cout << "summer\n";
            break;
        case 7:
        case 8:
        case 9:
            cout << "fall\n";
            break;
        case 10:
        case 11:
        case 12:
            cout << "winter\n";
            break;
    }
}

第三種解法

這題其實還有更簡單的解法,我們可以直接利用 if 加上不等式來判斷:

if (x >= 10) cout << "winter" << endl;
else if (x >= 7) cout << "fall" << endl;
else if (x >= 4) cout << "summer" << endl;
else cout << "spring" << endl;

完整的程式碼如下:

#include <iostream>
using namespace std;

int x;

int main() {
    cin >> x;
    if (x >= 10) cout << "winter" << endl;
    else if (x >= 7) cout << "fall" << endl;
    else if (x >= 4) cout << "summer" << endl;
    else cout << "spring" << endl;
}