#HW1_20220119 請撰寫以下程式,該程式必須具備防呆處理,規定詳見備註 : 1. 請使用者輸入一正整數:「數量」,該數值介於 2~20 之間。 2. 讓使用者重覆輸入數個正數 (允許小數) 做為數列,數列的個數和第一步驟的「數量」相同 (例如數量輸入 6 ,就讓使用者輸入 6 個正數)。 3. 從數列中找出「最大值」、「最小值」,並列出給使用者。 ****備註**** 1. 程式防呆包含:數值限制 (例如整數或浮點數檢查)、值域檢查 (例如 2~20)。 2. 所有步驟應有明確的提示,例如第一步驟應該要寫 「請輸入 2~20 的正整數」。 3. 如果使用者輸入錯誤時,給使用者三次機會重新輸入。 ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HW1 { class Program { static void Main(string[] args) { int x = 0; //用來記錄使用者出錯次數 Console.ForegroundColor = ConsoleColor.White; //美觀改個顏色(❁´◡`❁)不重要 while (true) //while迴圈,是防呆用的 { Console.ForegroundColor = ConsoleColor.White; double TempN = 0; //用來暫時存取讀取的正數,順便比大小 double TempN2 = 0; Console.Write("Please input an integer that between 2 and 20 : "); try { int num = Convert.ToInt32(Console.ReadLine()); //讓使用者輸入數字 if (num >= 2 && num <= 20) //必須介於2~20之間 { Console.WriteLine("Please input " + num + " positive numbers :"); for (int i = 1; i <= num; i++) //執行第一次輸入整數的次數 { double N = Convert.ToDouble(Console.ReadLine()); if (N > 0) //檢查是否大於0 { if (N > TempN) //最大值比較 TempN = N; if (i == 1) //暫時存取的 TempN2 = TempN; if (TempN2 > N) //最小值比較 TempN2 = N; if (i == num) //顯示最大值最小值 { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Maximum : " + TempN); Console.WriteLine("Minimum : " + TempN2); Console.ForegroundColor = ConsoleColor.White; Console.ReadLine(); return; } } else //數列輸入錯誤警告 { Console.ForegroundColor = ConsoleColor.Red; x++; Console.WriteLine("The input should be positive!!"); Ex(x); Console.ReadLine(); if (x == 3) //3次錯誤直接結束程式 { Console.WriteLine("Please open your eyes!!"); Console.ReadLine(); return; } } } } else //2~20輸入錯誤警告 { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Your input is wrong!!"); x++; Ex(x); if (x == 3) { Console.WriteLine("Please open your eyes!!"); Console.ReadLine(); break; } } } catch (Exception ex) //排除錯誤,避免卡機 { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex.ToString()); x++; Ex(x); if (x == 3) { Console.WriteLine("Please open your eyes!!"); Console.ReadLine(); break; } Console.ForegroundColor = ConsoleColor.White; } } } //Ex(); 讓使用者知道他手多殘 static void Ex(int x) { Console.ForegroundColor = ConsoleColor.DarkRed; Console.WriteLine("You have been wrong " + x + " time(s)!"); } } } ``` ![](https://i.imgur.com/IkLcXAs.png)