C# 实现矩阵的相乘

输入输出示例: 

 代码实现:

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方法,从而实现了输入一行再回车,让输入的数据具有矩阵的形式。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值