Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 2020/4/20(月)
- import java.util.Scanner;
- public class Gyoretsu4 {
- public static void main(String[] args) {
- int[] matrixSize = matrixDefine();
- if (matrixSize == null) return;
- matrixProduct(matrixSize[0], matrixSize[1], matrixSize[2], matrixSize[3]);
- }
- public static int[] matrixDefine() {
- Scanner scanner = new Scanner(System.in);
- int[] matrixSize = new int[4];
- System.out.println("2つの行列の積を求めます");
- System.out.println("1つめの行列の大きさ(行)を入力して下さい");
- matrixSize[0] = scanner.nextInt();
- System.out.println("1つめの行列の大きさ(列)を入力して下さい");
- matrixSize[1] = scanner.nextInt();
- System.out.println("2つめの行列の大きさ(行)を入力して下さい");
- matrixSize[2] = scanner.nextInt();
- System.out.println("2つめの行列の大きさ(列)を入力して下さい");
- matrixSize[3] = scanner.nextInt();
- if (matrixSize[1] != matrixSize[2]) {
- System.out.println("この2つの行列は(少なくともこの順では)積が求められません nullを返します");
- return null;
- }
- return matrixSize;
- }
- public static void matrixProduct(int A_row, int A_column, int B_row, int B_column) {
- Scanner scanner = new Scanner(System.in);
- double[][] A = new double[A_row][A_column];
- double[][] B = new double[B_row][B_column];
- double[][] P = new double[A_row][B_column];
- for (int i = 0; i < A_row; i++) {
- for (int j = 0; j < A_column; j++) {
- System.out.println("1つめの行列の" + (i + 1) + "行" + (j + 1) + "列の要素の値を入力して下さい(小数可)");
- A[i][j] = scanner.nextDouble();
- }
- }
- for (int i = 0; i < B_row; i++) {
- for (int j = 0; j < B_column; j++) {
- System.out.println("2つめの行列の" + (i + 1) + "行" + (j + 1) + "列の要素の値を入力して下さい(小数可)");
- B[i][j] = scanner.nextDouble();
- }
- }
- for (int i = 0; i < A_row; i++) {
- for (int j = 0; j < B_column; j++) {
- for (int k = 0; k < A_column /* B_rowでも同じ */ ; k++) {
- P[i][j] += A[i][k] * B[k][j];
- }
- System.out.println("求める積を表す行列の" + (i + 1) + "行" + (j + 1) + "列の要素の値は、" + P[i][j] + "です");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement