C#二維數組練習之求二維數組最大值以及求對角線的和

二維數組最大值查詢

  • 有⼀個3⾏4列的⼆維數組,要求編程找出最⼤元素,並輸出所在的⾏和列。

其實很簡單,就是兩兩比較保存角標就行。
直接上代碼:


			//首先定義一個3⾏4列的二維數組並初始化
            int[,] testArr01 = new int[3, 4]
            {
                { 34, 25, 60, 43 },
                { 55, 67, 21, 99 },
                { 2, 5, 88, 66 } };

            //循環遍歷求最大值,定義變量row,col保存角標
            int row = 0, col = 0;

            for (int i = 0; i < testArr01.GetLength(0); i++)
            {
                for (int j = 0; j < testArr01.GetLength(1); j++)
                {
                    if (testArr01[row, col] < testArr01[i, j])
                    {
                        row = i;
                        col = j;
                    }
                }
            }

            Console.WriteLine("該數組的最大值是:{0};它在第{1}行,第{2}列。", 
            testArr01[row, col], row + 1, col + 1);
            

求⼆維數組(3⾏3列)的對⻆線元素之和。

也是非常簡單,直接上代碼:


			//首先定義一個3⾏4列的二維數組並初始化
            int[,] testArr02 = new int[3, 3]
            {
                { 34, 25, 60 },
                { 55, 67, 21 },
                { 2, 5, 88 } };

            //定義sum01保存求和結果
            int sum01 = 0;

            for (int i = 0; i < testArr02.GetLength(0); i++)
            {
                sum01 += testArr02[i, i];
            }

            Console.WriteLine("該數列的對角線之和是:{0}。", sum01);
            

有疑問的可以私信博主。
點個關注,給個讚唄!

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