6

我试图用 c# 语言创建一个 3x3 矩阵,我知道如何创建矩阵,但我需要用户输入数字的帮助。我希望有人可以帮助我谢谢你。

4

3 回答 3

9

我将添加一个 while 循环并使用 double.TryParse 来验证用户的输入。使用 BWHazel 的代码:

const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;

double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];

for (int i = 0; i < MATRIX_ROWS; i++)
{
    for (int j = 0; j < MATRIX_COLUMNS; j++)
    {
        double input;
        Console.Write("Enter value for ({0},{1}): ", i, j);
        while (!double.TryParse(Console.ReadLine(), out input)
        {
            Console.Write("Enter correct value for ({0},{1}): ", i, j);
        }
        matrix[i,j] = input
    }
}

要获取所有行的总数,您可以使用以下代码段:

for (int i = 0; i < MATRIX_ROWS; i++) 
{
    // The some for each row
    double sum = 0.0;
    for (int j = 0; j < MATRIX_COLUMNS; j++)
    {
        sum += matrix[i,j];
    }
    Console.WriteLine(string.format("The sum for row {0} is: {1}", i, sum));
}
于 2013-10-07T10:12:47.800 回答
1

如果您使用的是命令行,这样的事情应该可以工作:

const int MATRIX_ROWS = 3;
const int MATRIX_COLUMNS = 3;

double[,] matrix = new double[MATRIX_ROWS, MATRIX_COLUMNS];

for (int i = 0; i < MATRIX_ROWS; i++)
{
    for (int j = 0; j < MATRIX_COLUMNS; j++)
    {
        Console.Write("Enter value for ({0},{1}): ", i, j);
        matrix[i,j] = double.Parse(Console.ReadLine());
    }
}

这假设您正在使用double这些值。该.Parse()方法适用于所有 .NET 数字类型,包括int.

于 2013-10-07T09:30:20.323 回答
0
    private void button1_Click(object sender, EventArgs e)
    {
        txtResult.Text=GenerateMatrix(Int32.Parse(txtRow.Text), Int32.Parse(txtColumn.Text));
    }
    private string GenerateMatrix(int Row,int Column)
    {
        string matrix = string.Empty;
        string Result = string.Empty;
        int nxtline=0;
        for (int i = 0; i < Row; i++)
        {
            for (int j = 0; j < Column; j++)
            {
                if (nxtline==Column)
                {
                    matrix = matrix + Environment.NewLine;
                    nxtline = 0;
                }
                matrix = matrix+"*";
                nxtline = nxtline + 1;
            }
        }

        Result = matrix;
        return Result;
    }
于 2018-09-07T06:52:30.947 回答