VB 控制台程序:矩阵加法、转置和乘法运算
下面是使用 VB 编写的控制台程序,实现矩阵加法、转置和乘法运算的代码:
Module Module1
Sub Main()
' 定义矩阵 A
Dim matrixA(,) As Integer = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
' 定义矩阵 B
Dim matrixB(,) As Integer = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}}
' 执行矩阵加法
Dim resultAddition(,) As Integer = MatrixAddition(matrixA, matrixB)
Console.WriteLine('矩阵加法的结果:')
PrintMatrix(resultAddition)
' 执行矩阵转置
Dim resultTranspose(,) As Integer = MatrixTranspose(matrixA)
Console.WriteLine('矩阵转置的结果:')
PrintMatrix(resultTranspose)
' 执行矩阵乘法
Dim resultMultiplication(,) As Integer = MatrixMultiplication(matrixA, matrixB)
Console.WriteLine('矩阵乘法的结果:')
PrintMatrix(resultMultiplication)
Console.ReadLine()
End Sub
' 矩阵加法
Function MatrixAddition(matrixA(,) As Integer, matrixB(,) As Integer) As Integer(,)
Dim rows As Integer = matrixA.GetLength(0)
Dim cols As Integer = matrixA.GetLength(1)
Dim result(rows - 1, cols - 1) As Integer
For i As Integer = 0 To rows - 1
For j As Integer = 0 To cols - 1
result(i, j) = matrixA(i, j) + matrixB(i, j)
Next
Next
Return result
End Function
' 矩阵转置
Function MatrixTranspose(matrix(,) As Integer) As Integer(,)
Dim rows As Integer = matrix.GetLength(0)
Dim cols As Integer = matrix.GetLength(1)
Dim result(cols - 1, rows - 1) As Integer
For i As Integer = 0 To rows - 1
For j As Integer = 0 To cols - 1
result(j, i) = matrix(i, j)
Next
Next
Return result
End Function
' 矩阵乘法
Function MatrixMultiplication(matrixA(,) As Integer, matrixB(,) As Integer) As Integer(,)
Dim rowsA As Integer = matrixA.GetLength(0)
Dim colsA As Integer = matrixA.GetLength(1)
Dim colsB As Integer = matrixB.GetLength(1)
Dim result(rowsA - 1, colsB - 1) As Integer
For i As Integer = 0 To rowsA - 1
For j As Integer = 0 To colsB - 1
Dim sum As Integer = 0
For k As Integer = 0 To colsA - 1
sum += matrixA(i, k) * matrixB(k, j)
Next
result(i, j) = sum
Next
Next
Return result
End Function
' 打印矩阵
Sub PrintMatrix(matrix(,) As Integer)
Dim rows As Integer = matrix.GetLength(0)
Dim cols As Integer = matrix.GetLength(1)
For i As Integer = 0 To rows - 1
For j As Integer = 0 To cols - 1
Console.Write(matrix(i, j) & " ")
Next
Console.WriteLine()
Next
End Sub
End Module
这段代码定义了一个 Main 函数作为程序的入口点,其中包含了矩阵加法、转置和乘法的实现函数,以及打印矩阵的辅助函数。
在 Main 函数中,首先定义了两个矩阵 matrixA 和 matrixB,然后依次调用矩阵加法、转置和乘法的函数,并将结果打印输出。最后通过 Console.ReadLine() 等待用户按下回车键,以保持控制台窗口打开。
原文地址: https://www.cveoy.top/t/topic/pjuI 著作权归作者所有。请勿转载和采集!