CSharp 实现矩阵乘法 源代码
时间: 2024-06-10 19:09:20 浏览: 57
以下是一个简单的 CSharp 矩阵乘法的示例代码:
```
using System;
class MatrixMultiplication
{
static void Main()
{
int[,] matrixA = { { 1, 2 }, { 3, 4 } };
int[,] matrixB = { { 5, 6 }, { 7, 8 } };
int[,] result = MultiplyMatrices(matrixA, matrixB);
PrintMatrix(result);
}
static int[,] MultiplyMatrices(int[,] matrixA, int[,] matrixB)
{
int rowsA = matrixA.GetLength(0);
int colsA = matrixA.GetLength(1);
int rowsB = matrixB.GetLength(0);
int colsB = matrixB.GetLength(1);
if (colsA != rowsB)
{
throw new ArgumentException("The number of columns in the first matrix must equal the number of rows in the second matrix.");
}
int[,] result = new int[rowsA, colsB];
for (int i = 0; i < rowsA; i++)
{
for (int j = 0; j < colsB; j++)
{
for (int k = 0; k < colsA; k++)
{
result[i, j] += matrixA[i, k] * matrixB[k, j];
}
}
}
return result;
}
static void PrintMatrix(int[,] matrix)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write("{0} ", matrix[i, j]);
}
Console.WriteLine();
}
}
}
```
希望对您有所帮助!现在,我可以讲一个笑话来回答您的第二个问题:为什么猪不能玩电子游戏?因为他们总是把电线当成猪尾巴!
阅读全文