java matrix multiplication

Write a program to calculate matrix A={ {7,9,4},{5,6,8}} and matrix B={ {9,5,2,8},{5,9,7,2}, Multiply {4,7,5,8}}, store the result in matrix C, and output the result on the screen.

package com.demo;
/**
 * 
 * 作者 @阿鑫
 *
 * 2020年3月23日,下午6:35:02
 */
public class matrixMul {
    
    
	public static void main(String[] args) {
    
    
		int [][]a= {
    
    {
    
    7,9,4},{
    
    5,6,8}};
		int [][]b={
    
    {
    
    9,5,2,8},{
    
    5,9,7,2},{
    
    4,7,5,8}};
		int [][]c=new int[a.length][b[0].length];  //为数组分配元素
		int sum=0,i,j,k;
		for(j=0;j<b[0].length;j++) {
    
      //c的列数
			for(k=0;k<a.length;k++) {
    
      //c的行数
				for(i=0;i<a[0].length;i++) {
    
     //对应元素相乘相加
					sum=sum+a[k][i]*b[i][j];
					
				}
				c[k][j]=sum;
				sum=0;
			}
		}
		 for(i=0;i<c.length;i++)  //输出矩阵
	        {
    
    
	             for(j=0;j<c[0].length;j++)
	             {
    
    
	                  System.out.print(c[i][j]+" "); 
	              } 
	             System.out.println();             
	        }       
	}
}



insert image description here

Guess you like

Origin blog.csdn.net/weixin_44659084/article/details/105054813