【问题标题】:How to make user defined rectangular array and itirate over it如何制作用户定义的矩形数组并对其进行迭代
【发布时间】:2021-11-30 04:25:40
【问题描述】:

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

这是我目前的代码 (on 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();
   };
}

【问题讨论】:

  • edit 并在问题中添加代码AS TEXT。 Why not upload images of code/errors when asking a question?
  • 你在哪里卡住了?
  • 约翰尼,图像是终端输出。它应该为每个文件和列打印 1 2 3 4 5 6 7 等。
  • 第一个建议,填充你的数组,然后打印出数组。它会简单得多.. 其次,您已经在第一个循环中跟踪行。所以只需删除if (file &gt; 0) {Console.WriteLine(" " + file);}; 并在第二个循环之后(第22 行之后)添加console.writeline(),最后你的第二个循环应该从1 开始。所以你不需要column + file + 1,而是列+文件就足够了。
  • 加分的附注 ;) 如果您使用 int.TryParse 而不是 int.Parse,您可以在用户执行不需要的操作(例如输入文本)时防止未处理的异常

标签: c# arrays multidimensional-array


【解决方案1】:

我建议将填充逻辑与打印分开。

人口逻辑几乎是好的。你只是不需要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();
}

【讨论】:

  • 非常感谢,它成功了。感谢您抽出宝贵时间。
  • 功劳归于@Behzad。我们最终得到了相同的解决方案,但他比我快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 2017-12-09
相关资源
最近更新 更多