[Day14]C# 鸡础观念- 不同层次的阵列~二维阵列

既然空间有维度,
阵列也像是空间一样,
他是拥有维度的,
就让我们探索看看吧

二维阵列/images/emoticon/emoticon52.gif

  • 就如同象棋棋盘,我们要知道旗子的位置,就得说他是第几行第几列
  • 结构如下

https://ithelp.ithome.com.tw/upload/images/20210912/20097001sufcdURA6n.png

  • 他看起来的样子就像
X 第0列 第1列 第2列
第0行 1 2 3
第1行 4 5 6
第2行 7 8 9
  • 使用方式跟一维阵列很像

范例:印出上面阵列的排列样子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsharpDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //宣告一个二维阵列
            int[,] Matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

            //开始照着阵列的样子排列吧
Console.Write(Matrix[0, 0]); Console.Write(Matrix[0, 1]); Console.WriteLine(Matrix[0, 2]);//第一行
Console.Write(Matrix[1, 0]); Console.Write(Matrix[1, 1]); Console.WriteLine(Matrix[1, 2]);//第二行
Console.Write(Matrix[2, 0]); Console.Write(Matrix[2, 1]); Console.WriteLine(Matrix[2, 2]);//第三行


            Console.ReadKey();
        }
    }
 }

结果:

123
456
789

使用for回圈处理二维阵列/images/emoticon/emoticon51.gif

  • 这部分比较进阶,需要使用两层的for回圈来处理

范例:使用双重for回圈,拆开二维阵列

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsharpDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //宣告一个二维阵列
            int[,] Matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

            //使用双重回圈
            //第一层,表示第几行
            for(int i=0; i < 3; i++)
            {
                //第二层,表示第几列,由於变数i已用过所以习惯上会用j
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(Matrix[i, j]+" ");
                }
                //我们这边要用一个特别的符号,换行符号"\n"在C#中表示换行
                Console.Write("\n");
            }

            Console.ReadKey();
        }
    }
 }

结果:

1 2 3
4 5 6
7 8 9

二维阵列可以做到XY轴的维度,但使用上也相对比较进阶了,所以有兴趣的朋友在深入研究


<<:  从 JavaScript 角度学 Python(14) - BMI 计算(2)

>>:  电子书阅读器上的浏览器 [Day15] 网页汇出成 epub 档案 (I)

Unity与Photon的新手相遇旅途 | Day22-Photon Lobby UI (下)

今天讲的内容为制作Lobby的一些基本简单UI(下集)。 ...

第 12 集:Sass 编译环境

此篇会介绍三种免费的 sass 编译方法。 Live Sass Compiler 这是一款免费 V...

Day 25:开始来学资料系结:事件系结(二)使用 $event 参数

前一篇我们谈到了事件系结的方法,在使用 事件系结(Event binding) 的时候,我们要先有一...

Unity与Photon的新手相遇旅途 | Day29-Unity 发布到Android手机上

今天的教学为教大家如何将Unity build完之後安装到Android手机上面测试。 ...

App 在发布到play商店後 Firebase Authentication 无法登入问题解决

身为一个App的开发新手常常会遇到一些莫名其妙又难以解决的问题,直到找到问题答案才发现根本是自己愚蠢...