Advertisement
Guest User

Untitled

a guest
Apr 21st, 2020
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. // 2020/4/20(月)
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class Gyoretsu4 {
  6. public static void main(String[] args) {
  7. int[] matrixSize = matrixDefine();
  8. if (matrixSize == null) return;
  9. matrixProduct(matrixSize[0], matrixSize[1], matrixSize[2], matrixSize[3]);
  10. }
  11.  
  12. public static int[] matrixDefine() {
  13. Scanner scanner = new Scanner(System.in);
  14. int[] matrixSize = new int[4];
  15. System.out.println("2つの行列の積を求めます");
  16. System.out.println("1つめの行列の大きさ(行)を入力して下さい");
  17. matrixSize[0] = scanner.nextInt();
  18. System.out.println("1つめの行列の大きさ(列)を入力して下さい");
  19. matrixSize[1] = scanner.nextInt();
  20. System.out.println("2つめの行列の大きさ(行)を入力して下さい");
  21. matrixSize[2] = scanner.nextInt();
  22. System.out.println("2つめの行列の大きさ(列)を入力して下さい");
  23. matrixSize[3] = scanner.nextInt();
  24. if (matrixSize[1] != matrixSize[2]) {
  25. System.out.println("この2つの行列は(少なくともこの順では)積が求められません nullを返します");
  26. return null;
  27. }
  28. return matrixSize;
  29. }
  30.  
  31. public static void matrixProduct(int A_row, int A_column, int B_row, int B_column) {
  32. Scanner scanner = new Scanner(System.in);
  33. double[][] A = new double[A_row][A_column];
  34. double[][] B = new double[B_row][B_column];
  35. double[][] P = new double[A_row][B_column];
  36. for (int i = 0; i < A_row; i++) {
  37. for (int j = 0; j < A_column; j++) {
  38. System.out.println("1つめの行列の" + (i + 1) + "行" + (j + 1) + "列の要素の値を入力して下さい(小数可)");
  39. A[i][j] = scanner.nextDouble();
  40. }
  41. }
  42. for (int i = 0; i < B_row; i++) {
  43. for (int j = 0; j < B_column; j++) {
  44. System.out.println("2つめの行列の" + (i + 1) + "行" + (j + 1) + "列の要素の値を入力して下さい(小数可)");
  45. B[i][j] = scanner.nextDouble();
  46. }
  47. }
  48. for (int i = 0; i < A_row; i++) {
  49. for (int j = 0; j < B_column; j++) {
  50. for (int k = 0; k < A_column /* B_rowでも同じ */ ; k++) {
  51. P[i][j] += A[i][k] * B[k][j];
  52. }
  53. System.out.println("求める積を表す行列の" + (i + 1) + "行" + (j + 1) + "列の要素の値は、" + P[i][j] + "です");
  54. }
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement