填充 C# 数组

问题描述 投票:0回答:2

我需要填充一个二维数组,但是需要最外面的2个边用1填充,其余的用0填充。

11111111111111111111
11111111111111111111
11000000000000000011
11000000000000000011
11000000000000000011
11000000000000000011
11000000000000000011
11000000000000000011
11111111111111111111
11111111111111111111

像这样。我如何为此设置循环?

我自己尝试过循环它,但我不是最擅长处理二维数组的。

c# multidimensional-array
2个回答
0
投票

您必须在嵌套循环中遍历两个索引,并根据

if either index < 2 or either index >= length - 2
:

将值设置为 1 或 0
int[,] array = new int[20,10];

for (int x = 0; x < array.GetLength(0); x++) {
    for (int y = 0; y < array.GetLength(1); y++) {
        if (x < 2 || x >= array.GetLength(0)-2 || y < 2 || y >= array.GetLength(1)-2) {
            array[x,y] = 1;
        } else {
            array[x,y] = 0;
        }
    }
}

我们在这里使用

array.GetLength(0)
而不是
array.Length
,因为
GetLength
每个轴维度的长度,而
array.Length
将返回元素总数 (200, 20x10),循环太多次。

如果您刚刚创建了一个新的

int
数组,默认情况下它们会填充 0,因此在这种情况下您可以只专注于设置 0。


0
投票

您需要两个

for
循环才能完成上述任务。

  1. 逐行循环一次
  2. 第二次循环遍历列

这样做时,您可以通过

if
条件检查它是否是边界。 请参阅下面解决方案中的边界检查 if 条件。

将相应的

1
0
分配给矩阵后一次。使用另外两个
for
循环相应地打印值。

参考以下代码:

using System;
                    
public class Program
{
    public static void Main()
    {
        int rows = 9; // define number of rows here
        int cols = 20; // define number of columns here

        int[,] matrix = new int[rows, cols];
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                if (i == 0 || i == rows - 1 || j == 0 || j == cols - 1) // check if it is boundry 
                {

                    matrix[i, j] = 1; // Set the value to 1 for the outermost sides
                }
                else
                {

                    matrix[i, j] = 0; // Set the value to 0 for all other positions
                }
            }
        }

        for (int i = 0; i < rows; i++) // for rows iteration
        {
            for (int j = 0; j < cols; j++) // for column iteration
            {
                Console.Write(matrix[i, j]); // Print values
            }
            Console.WriteLine(); // Print new line
        }

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.