首页 > 解决方案 > 如何制作用户定义的矩形数组并对其进行迭代

问题描述

所以,我有这个学校分配,我就是不能把它做好。我应该制作一个矩形数组,大小由用户定义,然后我必须打印数组中的所有值。它应该看起来像这样:

预期产出

到目前为止,这是我的代码(在 github 上):

static void Main(string[] args)
{
   Console.WriteLine("Ingrese un número entero: ");
   int userValue = int.Parse(Console.ReadLine()); //el número ingresado por el usuario es guardado en una variable
   if (userValue <= 10 && userValue > 0) //valida que el número ingresado sea igual o menor a 10 y mayor que 0
   {
        int[,] rectArray = new int[userValue,userValue]; //la variable que registra el número dado por el usuario es usada para definir el tamaño del arreglo
        Console.WriteLine("Los valores del arreglo son:");
        for (int file = 0; file < rectArray.GetLength(0); file++)
        {   
            if (file > 0) {Console.WriteLine(" " + file);}; //Se utiliza un condicional para evitar que se imprima la primer línea con valor de 0
            for (int column = 0; column < rectArray.GetLength(1); column++)
            {
                int colValue = column + file + 1;
                Console.Write(" " + colValue );
            };
        };
        Console.ReadKey();
   } 
    else
   {
       Console.WriteLine("El valor necesita ser igual o menor a 10.");
       Console.ReadKey();
   };
}

标签: c#arraysmultidimensional-array

解决方案


我建议将人口逻辑与打印分开。

人口逻辑几乎是好的。你只是不需要if声明:

int[,] rectArray = new int[userValue, userValue]; 
for (int row = 0; row < userValue; row++)
{
    for (int column = 0; column < userValue; column++)
    {
        rectArray[row, column] = column + row + 1;
    }
}

打印几乎相同,但您不需要为数组的每个元素分配值,而是需要检索它们:

for (int row = 0; row < rectArray.GetLength(0); row++)
{ 
    for (int column = 0; column < rectArray.GetLength(1); column++)
    {
        Console.Write(" " + rectArray[row, column]);
    }
    Console.WriteLine();
}

推荐阅读