如何将列添加到数组C

如何将列添加到数组C

本文介绍了如何将列添加到数组C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够创建一个通过使用而输入的动态数组,但是我需要一个用户不输入的起始固定数组:

i am able to create a dynamic array entered by the use, but i need to have a starting fixed array that is not entered by the user:

以下是示例:

输入并打印的数组是:

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

我需要像这样在数组的开头添加一列0:

I need to add a column of 0s at the beginning of the array like so:

0 1 2 3 4 5

0 1 2 3 4 5

0 1 2 3 4 5

0 1 2 3 4 5

0 1 2 3 4 5

0 1 2 3 4 5

谢谢!

推荐答案

假设您为r和c输入3行和2列.然后输入值.输出为:

Say you enter 3 rows and 2 columns for r and c. Then input the values. The output is:

1 2

1 2

1 2

但是现在我希望它显示为:

But now I want that to appear as:

0 1 2

0 1 2

0 1 2

行数(垂直)相同.但是,自从我将额外的列添加为0以来,列的数量(水平)从2增加到了3.

The number of rows (vertical) is the same. But the number of columns (horizontal) has increased from 2 to 3 since I've added the extra column for 0's.

因此,在代码中,我们必须考虑额外的列:

So in code we have to account for the extra column:

    int r;
    int c;
    Console.Write("Enter number of rows: ");
    r = (int)Convert.ToInt32(Console.ReadLine());
    Console.Write("Enter number of columns: ");
    c = (int)Convert.ToInt32(Console.ReadLine());
    c++; //add an extra column for the added 0's
    int[,] matrix = new int[r, c];

现在,我们要在此列中添加0.但是我们需要能够指定只为第一列添加0.当我们填充数组时,我们可以添加一个检查,说如果当前填充的列是一行的第一列,则自动插入0.

Now we want to add the 0's to this column. But we need to be able to specify that we only want to add 0's for the first column. When we're filling the arrays we can add a check to say that if the column we are currently filling is the very first column for a row then automatically insert a 0.

    for (int row = 0; row < r; row++)
    {
        for (int col = 0; col < c; col++)
        {
            if (col == 0)
            {
                matrix[row, col] = 0;
            }
            else
            {
                Console.Write("Enter value for matrix[{0},{1}] = ", row, col);
                matrix[row, col] = (int)Convert.ToInt32(Console.ReadLine());
            }
        }
    }

要求用户输入的第一个条目不再是{0,0},因为将自动输入第一个条目,但是您真的在乎吗?如果是这样,您可以从显示值减去1:

The first entry that the user is asked to enter is no longer {0,0} since the very first entry would've been automatically entered, but do you really care? If so you can just minus 1 from the display value there:

    Console.Write("Enter value for matrix[{0},{1}] = ", row, col -1);

这篇关于如何将列添加到数组C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 03:12