用C#中的用户输入填充矩阵

时间:2016-01-16 05:44:46

标签: c# arrays matrix input fill

我想用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

            }
        }

4 个答案:

答案 0 :(得分:1)

在输入数组大小之前分配内存。 正确的代码:

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( ) );
    }
}

答案 1 :(得分:0)

您将矩阵初始化为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());      } }

答案 2 :(得分:0)

        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());
            }
        }

答案 3 :(得分:0)

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();
}