--- tags: CSE --- # HW3 ## 題目說明 Objective : 學會使用 if/else 敘述作程式邏輯判斷。 ### 3-1 設計一個程式,於 xy 平面上輸入一點之座標後,判斷並輸 出其位於哪個象限上。 (提示:程式需可判斷點(0,0)位於何處) Input : (-2.5,-99)、(0,0) Output : ![](https://i.imgur.com/KoFY9Az.png =50%x) ### 3-2 設計一個程式,輸入水果的大小及甜度後,按下列標準判斷它屬於哪個級別。 大小 : 小(s)、中(m)、大(l)、超大(e) 甜度 : 一介於 1 到 100 之間的整數 分級標準: Premium class:**大或超大**,且**甜度 ≥ 85** Gifted class:**中或以上**,且**甜度 ≥ 60** Regular class:**不限大小**,**甜度 ≥ 40** Inferior class:**不限大小**,**甜度 < 40** (提示:應對錯誤的輸入值做出處理) Input : (m,72)、k Output: ![](https://i.imgur.com/vf9RUx4.png =50%x) ![](https://i.imgur.com/4q8SH0f.png =50%x) ## 程式碼 **3-1** ```c= printf("Please enter x coordinate : "); scanf("%f", &x); printf("Please enter y coordinate : "); scanf("%f", &y); ``` 簡單輸出輸入,x代表x,y代表y ```c=5 if (x>0 && y>0) { printf("point (%f,%f) is in the first quadrant.", x, y); } else if(x<0 && y>0) { printf("point (%f,%f) is in the second quadrant.", x, y); } else if(x<0 && y<0) { printf("point (%f,%f) is in the third quadrant.", x, y); } else if(x>0 && y<0) { printf("point (%f,%f) is in the fourth quadrant.", x, y); } else printf("point (%f,%f) is not in any quadrant.", x, y); ``` 接下來就是照著象限的定義去做if-else的判斷, 並且在線上的點也不用作x、y軸的判定, 因此只需要一個else輸出不在任何象限即可。 **3-2** 這題我也寫得很麻煩==, 但我現在腰好痠所以先隨便帶過:) ```c= char size; int sweet; ``` 宣告一個變數紀錄大小、一個變數紀錄數值 ```c=3 printf("Please enter size : "); scanf("%c", &size); ``` 要求使用者輸入大小 ```c=5 if(size != 's' && size != 'm' && size != 'l' && size != 'e') { printf("Wrong fruit size!!!"); return 0; } ``` 因為提示有要求應對錯誤的輸入值做出處理, 所以這裡很簡白的輸出錯誤訊息。 這邊寫了return 0是因為那時候我不知道還有什麼方法可以停止程式運行, 而且題目也沒有要求輸出錯誤訊息之後要做什麼。 (理論會希望你用while迴圈之類的重新輸出問題但我就隨便帶過囉) ```c=10 printf("Please enter sweetness : "); scanf("%d", &sweet); if(sweet < 1 || sweet >100) { printf("Wrong fruit sweetness!!!"); return 0; } ``` 跟上面大同小異,只是改成甜度的判定(1~100)。 ```c=17 if(sweet < 40) { printf("This fruit is Inferior class."); } ``` 這邊可以觀察題目,因為不限大小的關係, 加上更高標準的甜度都超過40, 所以可以直接透過甜度小於40判斷這是Inferior class。 ```c=21 else if(sweet < 60) { printf("This fruit is Regular class."); } ``` 跟上面想法一樣 ```c=25 else if(sweet >= 60 && sweet < 85 && size != 's') { printf("This fruit is Gifted class."); } ``` 這邊直接限定甜度的範圍, 並且設定大小不為「小」才能符合, 如此就滿足Gifted class的定義。 ```c=29 else if(sweet >= 85 && size != 's' && size != 'm') { printf("This fruit is Premium class."); } ``` 這邊也是將甜度範圍訂出來, 並設定大小不為「小」和「中」(也可以設定大小為「大」和「超大」), 就完成判定了。 另外這裡應該可以直接寫else就好, 因為在每次輸入時就會判定甜度和大小是否為合理範圍, 應該ㄅ。 這樣HW3就完成嚕, 我要去救我的腰了。