您的位置:首页 > 其它

计算两个矩阵的乘积

2017-02-23 16:05 190 查看
这里写代码片//计算两个矩阵相乘的程序
import java.io.*;
import java.util.Scanner;

class arraytest
{
public static void main(String args[])
{
int row = 0, col = 0;
System.out.println("请输入第一个矩阵的行数和列数:");
Scanner x = new Scanner(System.in);
row = x.nextInt();
Scanner y = new Scanner(System.in);
col = y.nextInt();

int array1[][] = new int[row][col];
Define(row,col,array1);
Print(row,col,array1);

int row1 = 0, col1 = 0;
System.out.println("请输入第二个矩阵的行数和列数:");
Scanner x1 = new Scanner(System.in);
row1 = x1.nextInt();
Scanner y1 = new Scanner(System.in);
col1 = y1.nextInt();
int array2[][] = new int[row1][col1];
Define(row1,col1,array2);
Print(row1,col1,array2);

Product(row,col,row1,col1,array1,array2);
}

//定义一个矩阵
public static int Define(int row , int col , int maxtril[][])
{
System.out.println("开始输入矩阵中的数:");
for(int i = 0;i < row;i++)
{
for(int j = 0;j < col;j++)
{
Scanner number = new Scanner(System.in);
maxtril[i][j] = number.nextInt();
}
}
return 1;
}

//显示一个矩阵
public static void Print(int row,int col,int maxtril[][])
{
System.out.println("开始输出:");
for(int i = 0;i < row;i++)
{
for(int j = 0;j < col;j++)
{
System.out.print(maxtril[i][j]);
System.out.print(" ");
}
System.out.println();
}
}

//计算两个矩阵的乘积
//如果第二个矩阵的行数跟第一个矩阵的列数不相同,则报错
public static void Product(int row1,int col1,int row2,int col2,int array1[][],int array2[][])
{
int matrix[][] = new int[row1][col2];
if(col1 != row2)
System.out.println("输入的矩阵有错");
else
{
for(int i = 0;i < row1;i++)
{
for(int j = 0;j < col2;j++)
{
matrix[i][j] = 0;
for(int k = 0;k < col1;k++)
{
matrix[i][j] += array1[i][k] * array2[k][j];
}
System.out.println();
}
}
Print(row1,col2,matrix);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: