iT邦幫忙

2021 iThome 鐵人賽

DAY 13
0
自我挑戰組

腦力激盪C++系列 第 13

[Day-13] 條件運算子以及switch小練習

這次就要來練習上次學習的switch
這邊我想了個題目來練習
那現在就開始練習程式碼吧!

題目:利用哈利波特中的普通巫術等級測驗,將成績輸入後轉換為普通巫術等級測驗。

Input:一個整數
Output:
100的分數為「O」傑出
90~99的分數為「E」超乎期待
80~89的分數為「A」合格
70~79的分數為「P」不佳
60~69的分數為「D」糟糕
其餘分數為「T」山怪

程式碼:

#include <iostream>
using namespace std;

int main(void){
    int score;
    cout << "Please input your score:";
    cin >> score;
    score = score/10;
    switch(score){
        case 10:
            cout << "Your level is " 
				 << "O" << '\n';
            break;
        case 9:
            cout << "Your level is " 
			     << "E" << '\n';
            break;
        case 8:
            cout << "Your level is "  
				 << "A" << '\n';
            break;
        case 7:
            cout << "Your level is " 
				 << "P" << '\n';
            break;
        case 6:
            cout << "Your level is " 
				 << "D" << '\n';
            break;
        default:
            cout << "Your level is " 
				 << "T" << '\n';
            break;
    }
}

執行結果:
100

Please input your score:100
Your level is O
--------------------------------
Process exited after 0.08787 seconds with return value 0
請按任意鍵繼續...

96

Please input your score:96
Your level is E
--------------------------------
Process exited after 0.08787 seconds with return value 0
請按任意鍵繼續...

87

Please input your score:87
Your level is A
--------------------------------
Process exited after 0.08787 seconds with return value 0
請按任意鍵繼續...

78

Please input your score:78
Your level is P
--------------------------------
Process exited after 0.08787 seconds with return value 0
請按任意鍵繼續...

66

Please input your score:66
Your level is D
--------------------------------
Process exited after 0.08787 seconds with return value 0
請按任意鍵繼續...

43

Please input your score:43
Your level is T
--------------------------------
Process exited after 0.08787 seconds with return value 0
請按任意鍵繼續...

程式碼解釋:

宣告變數score
利用cin將鍵盤輸入的成績存放到變數score
再讓變數score除以10
載入switch利用變數score找到相對應的case
並將結果顯示在命令提示字元上
執行完畢後break跳出迴圈
結束程式

舉例來說↓
輸入100
則會到switch的case 10執行
命令提示字元顯示「O」
Break跳出迴圈

輸入96
則會到switch的case 9執行
命令提示字元顯示「E」
Break跳出迴圈

輸入87
則會到switch的case 8執行
命令提示字元顯示「A」
Break跳出迴圈

例如輸入78
則會到switch的case 7執行
命令提示字元顯示「P」
Break跳出迴圈

例如輸入66
則會到switch的case 6執行
命令提示字元顯示「D」
Break跳出迴圈

例如輸入43
則會到switch的default執行
命令提示字元顯示「T」
Break跳出迴圈

以上就是我今天的練習~
/images/emoticon/emoticon08.gif

-End-

參考文章:http://www.crown.com.tw/harrypotter/375331_page04.html


上一篇
[Day-12] 條件運算子以及switch
下一篇
[Day-14] while迴圈
系列文
腦力激盪C++30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言