输入输出示例:
代码实现:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Console.Write("请输入第一个矩阵的行数:");
int m1 = Convert.ToInt32(Console.ReadLine());
Console.Write("请输入第一个矩阵的列数:");
int n1 = Convert.ToInt32(Console.ReadLine());
Console.Write("请输入第二个矩阵的行数:");
int m2 = Convert.ToInt32(Console.ReadLine());
Console.Write("请输入第二个矩阵的列数:");
int n2 = Convert.ToInt32(Console.ReadLine());
int[,] result = new int[m1, n2];
string[,] s1 = new string[m1, n1]; //将输入的矩阵放到字符串类型的二维数组中
string[,] s2 = new string[m2, n2];
Console.WriteLine("请输入第一个矩阵:");
for (int i = 0; i < s1.GetLength(0); i++) //遍历每一行
{
string temp = Console.ReadLine(); //将这一行的数据输入到字符串中,用空格分隔
string[] ttemp = temp.Split(" "); //利用Split分割每一个数据,存放到一个字符串数组里
for (int j = 0; j < s1.GetLength(1); j++) //遍历每一列,将字符串数组的数据放入到字符串类型的二维数组中
{
s1[i, j] = ttemp[j];
}
}
Console.WriteLine("请输入第二个矩阵:");
for (int i = 0; i < s2.GetLength(0); i++)
{
string temp = Console.ReadLine();
string[] ttemp = temp.Split(" ");
for (int j = 0; j < s2.GetLength(1); j++)
{
s2[i, j] = ttemp[j];
}
}
for (int i = 0; i < s1.GetLength(0); i++)
for (int j = 0; j < s2.GetLength(1); j++) { int sum = 0;
for (int k = 0; k < s1.GetLength(1); k++) { sum += int.Parse(s1[i, k]) * int.Parse(s2[k, j]); }
result[i, j] = sum;
}
Console.WriteLine("所得结果为:");
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++) Console.Write(result[i, j] + " ");
Console.WriteLine("");
}
}
}
这里在输入矩阵的时候利用Split方法,从而实现了输入一行再回车,让输入的数据具有矩阵的形式。