用用户在 C# 中的输入填充矩阵
本文关键字:输入 填充 用户 | 更新日期: 2023-09-27 18:30:40
我想用用户的输入在 C# 中填充一个矩阵,但我遇到了麻烦。当我输入彼此相等的行和列时,它可以工作; 但是当我输入彼此不同的行和列时,程序停止。 代码是
int row = 0;
int col = 0;
int[,] matrix1;
row = Convert.ToInt16(Console.ReadLine());
col = Convert.ToInt16(Console.ReadLine());
matrix1=new int[row,col];
Console.WriteLine("enter the numbers");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
matrix1[i, j] = Convert.ToInt16(Console.ReadLine());// i have problem with this line,... plz show me the correct form
}
}
在输入数组大小之前分配内存。正确的代码:
int row = 0;
int col = 0;
int[ , ] matrix1;
row = Convert.ToInt16( Console.ReadLine( ) );
col = Convert.ToInt16( Console.ReadLine( ) );
matrix1 = new int[ row, col ];
Console.WriteLine( "enter the numbers" );
for ( int i = 0; i < col; i++ )
{
for ( int j = 0; j < row; j++ )
{
matrix1[ i, j ] = Convert.ToInt16( Console.ReadLine( ) );
}
}
您将矩阵初始化为0x0矩阵。 这是一个空矩阵,因此您无法添加或读取任何内容。
试试这个
int row = 0;
int col = 0;
int[,] matrix1;
row = Convert.ToInt16(Console.ReadLine());
col = Convert.ToInt16(Console.ReadLine());
matrix1=new int[row,col];
Console.WriteLine("enter the numbers");
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++)
{
matrix1[i, j] = Convert.ToInt16(Console.ReadLine()); } }
int row;
int col;
row = Convert.ToInt16(Console.ReadLine());
col = Convert.ToInt16(Console.ReadLine());
int[,] matrix1 = new int[row, col];
Console.WriteLine("enter the numbers");
for (int i = 0; i < col; i++)
{
for (int j = 0; j < row; j++)
{
matrix1[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
int col = Convert.ToInt32(Console.ReadLine());
int row = Convert.ToInt32(Console.ReadLine());
int[,] matrix = new int[row, col];
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"enter row{i} and col{j} ");
matrix[i, j] = Convert.ToInt16(Console.ReadLine());
}
Console.WriteLine();
}
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j]);
}
Console.WriteLine();
}