以矩阵格式打印2D阵列 [英] Printing 2D array in matrix format

查看:55
本文介绍了以矩阵格式打印2D阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2D数组,如下所示:

I have a 2D array as follows:

long[,] arr = new long[4, 4] {{ 0, 0, 0, 0 },
                              { 1, 1, 1, 1 },
                              { 0, 0, 0, 0 },
                              { 1, 1, 1, 1 }};

我想以矩阵格式打印此数组的值:

I want to print the values of this array in matrix format like:

0 0 0 0
1 1 1 1
0 0 0 0
1 1 1 1

我该怎么做?

推荐答案

您可以按以下步骤进行操作(对数组进行稍加修改以显示其适用于非正方形数组):

You can do it like this (with a slightly modified array to show it works for non-square arrays):

        long[,] arr = new long[5, 4] { { 1, 2, 3, 4 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } };

        int rowLength = arr.GetLength(0);
        int colLength = arr.GetLength(1);

        for (int i = 0; i < rowLength; i++)
        {
            for (int j = 0; j < colLength; j++)
            {
                Console.Write(string.Format("{0} ", arr[i, j]));
            }
            Console.Write(Environment.NewLine + Environment.NewLine);
        }
        Console.ReadLine();

这篇关于以矩阵格式打印2D阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆