[練習] 輸入10個整數統計偶數個數

 

    public class MainClass
    {
        public static int countEventNum(int[] arr)
        {
            try      //可能出現異常的語句快
           
            {
                int count = 0;
                for (int i = 0; i < arr.Length; i++)
                {
                    if (arr[i] % 2 == 0)
                    {
                        count++;
                    }
                }
                return count;
            }
            catch (Exception ex)    // 若有異常,在此拋出
            {
                throw ex;
            }
        }
    }
    class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                string s;
                int i = 0;
                int[] a = new int[10];
                while (i < a.Length)
                {
                    Console.Write("請輸入第{0}個整形數字:", i + 1);
                    s = Console.ReadLine();
                    int.TryParse(s, out a[i]);  //使用TryParse方法代替無效轉型異常
                    i++;
                }
                int k = MainClass.countEventNum(a); //調用統計偶數個數方法
                Console.WriteLine("偶數個數是" + k.ToString());
                Console.ReadKey(false);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

 

}

//不輸入視爲偶數(可能視爲0)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章