zoukankan      html  css  js  c++  java
  • 计算矩阵的乘积

    问题:

      编写程序,计算两矩阵a与b的乘积,并输出结果

    分析:

      根据两矩阵相乘的规则,矩阵a的列数应与矩阵b的行数相同。若a是4行3列矩阵,b是3行2列矩阵,设乘积为c,则c是4行两列矩阵,由于数学上的矩阵恰好和C语言上二维数组相对应,因此本例说明三个二维数组变量,其所分配的存储空间恰好可以存放a、b、c三个矩阵所有的元素值,为简便计,不妨设矩阵元素为整型数值,矩阵a、b的元素值均由键盘输入,为增强直观性,希望所输入的数据以及输出的结果数据形式均与矩阵的书写顺序相对应,,即各矩阵按行列左右分开、上下对齐。

     1 //实现任意两个矩阵的乘积,并输出结果 
     2 #include<stdio.h>
     3 int main(){
     4     int i,j,k,s;
     5     int M,P,X,Y;
     6     printf("Enter your first of matrix a rows and cols:"); 
     7     scanf("%d %d",&M,&P); 
     8     printf("Enter your second of matrix a rows and cols:");
     9     scanf("%d %d",&X,&Y); 
    10     int a[M+1][P+1],b[X+1][Y+1],c[M+1][Y+1];
    11     printf("Enter the elements of matrix a(%d*%d):
    ",M,P);
    12     for(i=1;i<=M;i++)
    13         for(j=1;j<=P;j++)
    14             scanf("%d",&a[i][j]);
    15     printf("
    ");
    16     printf("Enter the elements of matrix b(%d*%d):
    ",X,Y);
    17     for(j=1;j<=X;j++)
    18         for(k=1;k<=Y;k++){
    19             scanf("%d",&b[j][k]);
    20         }
    21     printf("
    
    ");
    22     printf("The result of a*b is
    ");
    23     for(i=1;i<=M;i++){
    24         for(k=1;k<=Y;k++){
    25             s=0;
    26             for(j=1;j<=X;j++)
    27                 s+=a[i][j]*b[j][k];
    28             c[i][k]=s;
    29             printf("%6d",s); 
    30         }
    31         printf("
    ");
    32     }        
    33     return 0;
    34 }






  • 相关阅读:
    git命令评测
    so文件成品评论【整理】
    Codeforces 85B. Embassy Queue【段树、馋】
    JPEG图像扩展信息读取和修改
    【 D3.js 入门系列 --- 0 】 简介及安装
    unity3d 学习笔记(三)
    ListView 泛利
    [React] Create an Auto Resizing Virtualized List with react-virtualized
    [PReact] Integrate Redux with Preact
    [Preact] Integrate react-router with Preact
  • 原文地址:https://www.cnblogs.com/geziyu/p/8783491.html
Copyright © 2011-2022 走看看