我想在C#中使用一些簡單的循環來添加兩個矩陣。我將結果存儲在數據網格視圖中。但是,最後一個單元格似乎沒有添加。我一直在看這個代碼一段時間,似乎無法弄清楚。我做錯什麼了嗎?在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];
}
}
}
對不起,我打算解決這個問題,當矩陣相乘時你如何確定矩陣的大小 – Kredns 2009-02-23 00:45:33
另外,請記住當.AllowUserToAddRows == true – 2009-02-23 00:56:34