J'essaie d'ajouter deux matrices ensemble en C# en utilisant des boucles simples pour les boucles. Je stocke les résultats dans une vue de grille de données. Cependant, la dernière cellule ne semble pas ajouter. Je regarde ce code depuis un moment maintenant et n'arrive pas à le comprendre. Est-ce que j'ai fait quelque chose de mal?Ajout de matrices en 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];
}
}
}
Désolé, je vais corriger cela, il s'avère que c'est ainsi que vous déterminez la taille d'une matrice lors de la multiplication des matrices – Kredns
Aussi, rappelez-vous que .RowCount sera éteint par un quand .AllowUserToAddRows == vrai –
Je l'avais déjà défini sur false car il ajoutait automatiquement des lignes et créait une situation difficile. – Kredns