C#二位数组 数组矩阵对角线之和

末鹿安然 提交于 2019-12-05 03:15:49

二维数组:

        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("");
            }
        }

 

    //  求矩阵对角线之和

   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);        }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!