-
Notifications
You must be signed in to change notification settings - Fork 4
/
矩阵相乘.txt
75 lines (74 loc) · 1.73 KB
/
矩阵相乘.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
public class MatrixMultiply
{
public static void Main()
{
int a,b,c,d;
Console.WriteLine ("该程序将求出两个矩阵的积:");
Console.WriteLine ("请指定矩阵A的行数:");
a=int.Parse (Console.ReadLine ());
Console.WriteLine ("请指定矩阵A的列数:");
b=int.Parse (Console.ReadLine ());
int[,] MatrixA=new int [a,b];
for(int i=0;i<a;i++)
{
for(int j=0;j<b;j++)
{
Console.WriteLine ("请输入矩阵A第{0}行第{1}列的值:",i+1,j+1);
MatrixA[i,j]=int.Parse (Console.ReadLine ());
}
}
Console.WriteLine ("矩阵A输入完毕.");
Console.WriteLine ("请指定矩阵B的行数:");
c=int.Parse (Console.ReadLine ());
Console.WriteLine ("请指定矩阵B的列数:");
d=int.Parse (Console.ReadLine ());
int[,] MatrixB=new int [c,d];
for(int i=0;i<c;i++)
{
for(int j=0;j<d;j++)
{
Console.WriteLine ("请输入矩阵A第{0}行第{1}列的值:",i+1,j+1);
MatrixB[i,j]=int.Parse (Console.ReadLine ());
}
}
Console.WriteLine ("矩阵B输入完毕.");
Console.WriteLine ("矩阵A为:");
outputMatrix(MatrixA,a,b);
Console.WriteLine ("矩阵B为:");
outputMatrix(MatrixB,c,d);
if(b!=c)
{
Console.WriteLine ("矩阵A的列数与矩阵B的行数不相等,无法进行乘积运算!");
return;
}
else
{
Console.WriteLine ("矩阵A与矩阵B的乘积为:");
}
int[,] MatrixC=new int [a,d];
for(int i = 0; i < a; i++)
{
for(int j = 0; j < d; j++)
{
MatrixC[i,j] = 0;
for(int k = 0; k < b; k++)
{
MatrixC[i,j] += MatrixA[i,k] * MatrixB[k,j];
}
}
}
outputMatrix(MatrixC,a,d);
}
private static void outputMatrix(int[,] MatrixX, int rowCount, int columnCount)
{
for(int i = 0; i < rowCount; i++)
{
for(int j = 0; j < columnCount; j++)
{
Console.Write(MatrixX[i,j] + "\t");
}
Console.WriteLine();
}
}
}