我正在尝试使用一些简单的 for 循环在 C# 中将两个矩阵相加。我将结果存储在数据网格视图中。但是,最后一个单元格似乎没有添加。我一直在看这段代码一段时间,似乎无法弄清楚。我做错什么了吗?
// Adds two matrices together using arrays.
private void menuItemAdd_Click(object sender, EventArgs e)
{
// Create two 2-D arrays
int[,] matrixOne = new int[dgvMatrixOne.RowCount, dgvMatrixOne.ColumnCount];
int[,] matrixTwo = new int[dgvMatrixTwo.RowCount, dgvMatrixTwo.ColumnCount];
// The rows of the total matrix match the rows of the first matrix.
dgvMatrixTotal.RowCount = dgvMatrixOne.RowCount;
// The columns of the total matrix match the columns of the first matrix.
dgvMatrixTotal.ColumnCount = dgvMatrixOne.ColumnCount;
// Fill matrix one with the data in the data grid matrix one.
for (int i = 0; i < dgvMatrixOne.RowCount; i++)
{
for (int j = 0; j < dgvMatrixOne.ColumnCount; j++)
{
matrixOne[i, j] = Convert.ToInt32(dgvMatrixOne[i, j].Value);
}
}
// Fill matrix two with the data in the data grid matrix two.
for (int i = 0; i < dgvMatrixTwo.RowCount; i++)
{
for (int j = 0; j < dgvMatrixTwo.ColumnCount; j++)
{
matrixTwo[i, j] = Convert.ToInt32(dgvMatrixTwo[i, j].Value);
}
}
// Set the total data grid to matrix one + matrix two.
for (int i = 0; i < dgvMatrixOne.RowCount; i++)
{
for (int j = 0; j < dgvMatrixOne.ColumnCount; j++)
{
dgvMatrixTotal[i, j].Value = matrixOne[i, j] + matrixTwo[i, j];
}
}
}