Java教程

java运用二维数组随机数进行矩阵加减乘和转置

本文主要是介绍java运用二维数组随机数进行矩阵加减乘和转置,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

import java.util.Random;
import java.util.Scanner;
public class 矩阵运算{
public static void main(String args[]){ Random ran=new Random();
int h1 =0;
int l1 =0;
int h2=0;
int l2=0;
for(int i = 0;i<1;i++) {
h1 =ran.nextInt(3)+2;
l1 =ran.nextInt(3)+2; h2=ran.nextInt(3)+2;
l2 =ran.nextInt(3)+2;
}
int[][] arr1=new int[h1][l1];
int[][] arr2=new int[h2][l2]; System.out.println(“第一个矩阵为:”); for(int i=0;i<h1;i++){
for(int j=0;j<l1;j++){
int x =ran.nextInt(3);
arr1[i][j]=x;
System.out.print(arr1[i][j]+" “);
}
System.out.println(” ");
}

System.out.println(“第二个矩阵为:”); for(int i=0;i<h2;i++){
for(int j=0;j<l2;j++){
int x =ran.nextInt(3);
arr2[i][j]=x;
System.out.print(arr2[i][j]+" “);
}
System.out.println(” ");
}
Scanner sc =new Scanner(System.in); System.out.println(“请选择你要进行的操作:”);
System.out.println(“1.矩阵转置”); System.out.println(“2.矩阵相加”); System.out.println(“3.矩阵相减”); System.out.println(“4.矩阵相乘”); System.out.println(“请输入1-4:”);
int n =sc.nextInt();

if(n==1){
System.out.println(“第一个矩阵转置为:”); int [][]a1 =new int[l1][h1];
for(int i=0;i<l1;i++){
for(int j=0;j<h1;j++){
int x =ran.nextInt(3);
a1[i][j]=arr1[j][i]; System.out.print(a1[i][j]+" “);
}
System.out.println(” “);
}
System.out.println(“第二个矩阵转置为:”); int [][]a2 =new int[l2][h2];
for(int i=0;i<l2;i++){
for(int j=0;j<h2;j++){
int x =ran.nextInt(3);
a2[i][j]=arr2[j][i]; System.out.print(a2[i][j]+” “);
}
System.out.println(” ");
}
}

else if(n2){
if(h1
h2&&l1==l2){ System.out.println (“两矩阵相加为:”);
int [][] jia=new int[h1][l1];
for ( int i = 0 ; i < h1; i++ ) {
for ( int j = 0 ; j <l1; j++ ) { jia[i][j] = arr1[ i ][ j ] + arr2[ i ][ j ]; System.out.print ( jia[i][j]+" “); } System.out.println (” ");
}
}
else {
System.out.println(“行数和列数不相等”);
}
}

else if(n==3){   

if(h1==h2&&l1==l2){       
 System.out.println("两矩阵相减为:");        
 int [][] jian=new int[h1][l1];       
  for ( int i = 0 ; i < h1; i++ ) {            
  for ( int j = 0 ; j <l1; j++ ) {               
   jian[i][j] = arr1[ i ][ j ] - arr2[ i ][ j ];                    System.out.print (jian[i][j]+" ");            
   }            
   System.out.println (" ");       
    }   
     }    
     else {        
     System.out.println("行数和列数不相等");
        }

}else if(n4){
if(l1
h2){
System.out.println(“两矩阵相乘为:”); int [][] cheng=new int[h1][l2];
for ( int i = 0 ; i < h1; i++ ) {
for ( int j = 0 ; j <l2; j++ ) {
for(int z =0;z<l2;z++){//l1 cheng[i][j]+= arr1[ i ][ z ] * arr2[ z ][ j ]; }
System.out.print (cheng[i][j]+" “);
}
System.out.println (” ");
}
} else {
System.out.println(“arr1列数和arr2的行数不相等,不能运算”);
}
}else{ System.out.println(“输入错误,强行结束”);
}
}
}

这篇关于java运用二维数组随机数进行矩阵加减乘和转置的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!