每日練習——2016.2.23

1.聲明兩個變量:int n1 = 10, n2 = 20;要求將兩個變量交換,最後輸出n1爲20,n2爲10。擴展(*):不使用第三個變量如何交換? 
             //方法一
            int n1 = 10;
            int n2 = 20;
            int item = n1;//第三方變量
            n1 = n2;
            n2 = item;
            Console.WriteLine("n1={0},n2={1}", n1, n2);
            Console.ReadKey();


            //方法二
            int n1 = 10;
            int n2 = 20;
            n2 = n1 + (n1 = n2) * 0;//根據執行順序實現交換值
            Console.WriteLine("n1={0},n2={1}", n1, n2);
            Console.ReadKey();


            //方法三 建造函數
            int n1 = 10;
            int n2 = 20;
            Exchange(ref n1, ref n2);
            Console.WriteLine("n1={0},n2={1}", n1, n2);
            Console.ReadKey();

            #endregion

                  ///計算兩個數的最大值得函數。 

                  private static void Exchange(ref int n1,ref int n2)
                 {
                       int item = n1;
                       n1 = n2;
                       n2 = item;
                 }

2.      #region 計算任意多個數之間的平均數?


            List<int> array = new List<int>();
            while (true)
            {
                Console.WriteLine("請輸入一個數字");
                int a = int.Parse(Console.ReadLine());//輸入一個數字
                array.Add(a);//存入到泛型數組中。
                Console.WriteLine("是否繼續輸入數字(Y/N)?");
                string yesOrNo = Console.ReadLine();//選擇是否繼續輸入
                if (yesOrNo == "N")
                {
                    break;
                }
            }
            double average = Avg(array);
            Console.WriteLine(average);
            Console.ReadKey();      
            #endregion


         /// <summary>
        /// 計算平均數
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        private static double Avg(List<int> array)
        {
            double sum = 0;
            foreach(int i in array)
            {
                sum += i;
            }
            return sum / array.Count;
        }
 


  3   #region 請用戶輸入一個字符串,計算字符串中的字符個數,並輸出。


            Console.WriteLine("請輸入一段字符串");
            string str = Console.ReadLine();
            Console.WriteLine(str.Length);
            Console.ReadKey();


     #endregion


 4.     #region  計算1-100之間的所有整數的和
            int sum = 0;
            for (int i = 1; i <= 100; i++)
            {
                sum += i;
            }
            Console.WriteLine("1-100之間所有整數的和:{0}:", sum);
            Console.ReadKey();
            #endregion



5.    #region 5.計算1-100之間的所有奇數的和。
            int sum = 0;
            for(int i=1;i<=100;i++)
            {
                if(i%2==1)
                {
                    sum += i;
                }
            }
            Console.WriteLine("1-100之間的所有奇數的和爲{0}",sum);
            Console.ReadKey();
            #endregion

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