題目:
讓使用者輸入生日(月 日)
輸出使用者的星座為何? (英文與日期對應以下面網站為主,注意大小寫)
https://davytw.pixnet.net/blog/post/58102131
例如: 輸入2 28,輸出: Pisces
解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| #include <iostream> using namespace std;
int main(){ int x;//月 int y;//日 cin >> x; cin >> y;
if(x == 1 && y >=21){ cout << "Aquarius" << "\n"; } else if(x == 2 && y <=19){ cout << "Aquarius" << "\n"; } else if(x == 2 && y >=20){ cout << "Pisces" << "\n"; } else if(x == 3 && y <=20){ cout << "Pisces" << "\n"; } else if(x == 3 && y >=21){ cout << "Aries" << "\n"; } else if(x == 4 && y <=19){ cout << "Aries" << "\n"; } else if(x == 4 && y >=20){ cout << "Taurus" << "\n"; } else if(x == 5 && y <=20){ cout << "Taurus" << "\n"; } else if(x == 5 && y >=21){ cout << "Gemini" << "\n"; } else if(x == 6 && y <=21){ cout << "Gemini" << "\n"; } else if(x == 6 && y >=22){ cout << "Cancer" << "\n"; } else if(x == 7 && y <=22){ cout << "Cancer" << "\n"; } else if(x == 7 && y >=23){ cout << "Leo" << "\n"; } else if(x == 8 && y <=22){ cout << "Leo" << "\n"; } else if(x == 8 && y >=23){ cout << "Virgo" << "\n"; } else if(x == 9 && y <=22){ cout << "Virgo" << "\n"; } else if(x == 9 && y >=23){ cout << "Libra" << "\n"; } else if(x == 10 && y <=23){ cout << "Libra" << "\n"; } else if(x == 10 && y >=24){ cout << "Scorpio" << "\n"; } else if(x == 11 && y <=21){ cout << "Scorpio" << "\n"; } else if(x == 11 && y >=22){ cout << "Sagittarius" << "\n"; } else if(x == 12 && y <=20){ cout << "Sagittarius" << "\n"; } else if(x == 12 && y >=21){ cout << "Capricorn" << "\n"; } else if(x == 1 && y <=20){ cout << "Capricorn" << "\n"; } return 0; }
|
解釋與詳細介紹
第一部分:if/else介紹
這題會用到一個新的概念,if/else迴圈。
1 2 3 4 5 6 7 8
| if (/*condition1*/) { /*statement1*/ } else { /*statement2*/ }
|
他是用於在條件選擇上,當”條件1”達成時(意即:條件一為true的情況),便會執行第一個大括號中的程式段(狀況1);反之則會執行else內的程式段(狀況2)。而使用者也可以依據情況在第一個if後,列多個else if(){}代表更多種不同的條件,最後一項再加上else{}。像是這題便會用到這種方式。
要注意的是,因為if(){}與else{}是相關聯的程式區段,所以在if()、else if()、else和多個{}後不會加上”;”。並且我們習慣將除了第一個if以外的條件式以縮排一個的方式呈現
第二部分:主功能解析
首先在這題中,我們可以明確分為
input:代表月、日的兩個整數數字
output:那天所屬於星座的英文名字
因為這題在判定星座上,需要自行為程式寫下判斷依準,我們以多個if/else的重複遞寫方式來達成(這裡先以if/else為例,讀者也可以搜尋case語法自己試看看!)
我們先令了兩個變數x(代表月),y(代表日),並將if()內的條件固定設為月與日的範圍限制。這裡會介紹到在條件判定裡面,我們常會使用到三種符號
==:代表判定是否相等這件事
(注意他與=:直接賦予”值”給變數的意思是不同的喔,像是x==3是一個判斷句,答案為true或false,而x=3則是”直接”使x的值賦予為3!)
=、<=:代表判定大於等於與小於等於的事件
&&:代表”皆為true”(and),||:代表”其中之一為true”(or)
在運用這些知識後,就可以組出這題的零件了!那我們明天見!
第三部分:成果展示
