C#二位數組 數組矩陣對角線之和

二維數組:數組

        public static void Main(string[] args)
        {

            int[,] a = new int[3, 3];
            Random rom = new Random();
            for (int x = 0; x < a.GetLength(0); x++)
            {
                for (int y = 0; y < a.GetLength(1); y++)
                {
                    a[x, y] = rom.Next(31);
                    Console.Write("{0} ", a[x, y]);
                }
                Console.WriteLine("");
            }
        }

 //  求矩陣對角線之和dom

  public static void Main(string[] args)
        {

            int[,] a= new int[3, 3];

            Random rnd = new Random();
            int a1 = 0;
            int a2 = 0;
            for (int x = 0; x < a.GetLength(0); x++)
            {
                for (int y = 0; y < a.GetLength(1); y++)
                {
                    a[x, y] = rnd.Next(21);
                    Console.Write("{0}  ", a[x, y]);
                    if (x == y)
                    {
                        a1 += a[x, y]; //統計正對角線元素之和
                    }
                    if (x + y == a.GetLength(0) - 1)
                    {
                        a2 += a[x, y]; //統計副對角線元素之和
                    }
                }
                Console.WriteLine("");
            }
            Console.WriteLine("正對角線元素之和:{0}", a1);
            Console.WriteLine("副對角線元素之和:{0}", a2);
        }
相關文章
相關標籤/搜索