C# 控制台程序:矩阵加法、转置和乘法运算
以下是使用 C# 语言编写的控制台程序示例,该程序可以实现输入两个矩阵并进行矩阵加法、转置和乘法运算。
using System;
namespace MatrixOperations
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine('Enter the number of rows for Matrix A: ');
int rowsA = Convert.ToInt32(Console.ReadLine());
Console.WriteLine('Enter the number of columns for Matrix A: ');
int colsA = Convert.ToInt32(Console.ReadLine());
Console.WriteLine('Enter the number of rows for Matrix B: ');
int rowsB = Convert.ToInt32(Console.ReadLine());
Console.WriteLine('Enter the number of columns for Matrix B: ');
int colsB = Convert.ToInt32(Console.ReadLine());
int[,] matrixA = new int[rowsA, colsA];
int[,] matrixB = new int[rowsB, colsB];
Console.WriteLine('Enter the elements of Matrix A: ');
for (int i = 0; i < rowsA; i++)
{
for (int j = 0; j < colsA; j++)
{
matrixA[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine('Enter the elements of Matrix B: ');
for (int i = 0; i < rowsB; i++)
{
for (int j = 0; j < colsB; j++)
{
matrixB[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
// 矩阵加法
if (rowsA == rowsB && colsA == colsB)
{
int[,] sumMatrix = new int[rowsA, colsA];
Console.WriteLine('Matrix Addition Result:');
for (int i = 0; i < rowsA; i++)
{
for (int j = 0; j < colsA; j++)
{
sumMatrix[i, j] = matrixA[i, j] + matrixB[i, j];
Console.Write(sumMatrix[i, j] + '\t');
}
Console.WriteLine();
}
}
else
{
Console.WriteLine('Matrix addition is not possible as the dimensions of the matrices are not same.');
}
// 矩阵转置
Console.WriteLine('Matrix A Transpose:');
for (int i = 0; i < colsA; i++)
{
for (int j = 0; j < rowsA; j++)
{
Console.Write(matrixA[j, i] + '\t');
}
Console.WriteLine();
}
Console.WriteLine('Matrix B Transpose:');
for (int i = 0; i < colsB; i++)
{
for (int j = 0; j < rowsB; j++)
{
Console.Write(matrixB[j, i] + '\t');
}
Console.WriteLine();
}
// 矩阵乘法
if (colsA == rowsB)
{
int[,] productMatrix = new int[rowsA, colsB];
Console.WriteLine('Matrix Multiplication Result:');
for (int i = 0; i < rowsA; i++)
{
for (int j = 0; j < colsB; j++)
{
int sum = 0;
for (int k = 0; k < colsA; k++)
{
sum += matrixA[i, k] * matrixB[k, j];
}
productMatrix[i, j] = sum;
Console.Write(productMatrix[i, j] + '\t');
}
Console.WriteLine();
}
}
else
{
Console.WriteLine('Matrix multiplication is not possible as the number of columns in Matrix A is not equal to the number of rows in Matrix B.');
}
Console.ReadLine();
}
}
}
注意:
- 以上代码使用 C# 语言编写,而不是 VB 语言。如果您需要在 VB 中编写类似的代码,则需要进行相应的语法和语言转换。
- 代码中包含详细注释,可以帮助您理解代码逻辑。
- 您可以根据自己的需求修改代码,例如:
- 更改矩阵元素的数据类型(例如:float、double)。
- 添加其他矩阵运算,例如:减法、除法。
- 将控制台输出保存到文件。
原文地址: https://www.cveoy.top/t/topic/pjwe 著作权归作者所有。请勿转载和采集!