c# - 如何制作用户定义的矩形数组并对其进行迭代
问题描述
所以,我有这个学校分配,我就是不能把它做好。我应该制作一个矩形数组,大小由用户定义,然后我必须打印数组中的所有值。它应该看起来像这样:
到目前为止,这是我的代码(在 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();
};
}
解决方案
我建议将人口逻辑与打印分开。
人口逻辑几乎是好的。你只是不需要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();
}
推荐阅读
- php - PHP - 执行功能不适用于内爆
- python-2.7 - 由于 mpl_toolkits,cx_Freeze 无法冻结脚本
- excel - 如何使用两列在excel中计数
- firebase - Firebase 数据库规则:无法读取另一个集合
- javascript - Framework 7 Vue 如何阻止 Firebase 在不同页面上监听更改?
- javascript - 使用 D3 包装器的折线图颜色
- apache - 如何减少此重定向链?或者至少,我怎样才能使某些部分服务器端?
- transactions - ejabberd“高”数量的中止交易 - 我应该担心吗?
- java - Java 进程错误无法运行程序
- ffmpeg - 用 libav / ffmpeg 替换 Bento4