您的位置:首页 > 编程语言

7-6 编程练习题答案

2014-06-21 14:59 477 查看
import java.util.Scanner;

public class Test
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double[][] matrix1 = new double[3][3];
double[][] matrix2 = new double[3][3];

System.out.print("Enter matrix1: ");
for(int i = 0; i < matrix1.length; i++)
for(int j = 0; j < matrix1[i].length; j++)
matrix1[i][j] = input.nextDouble();

System.out.print("Enter matrix2: ");
for(int i = 0; i < matrix2.length; i++)
for(int j = 0; j < matrix2[i].length; j++)
matrix2[i][j] = input.nextDouble();

double[][] answers = multiplyMatrix(matrix1, matrix2);

System.out.println("The matrices are multiplied as follows; ");
System.out.println(matrix1[0][0] + " " + matrix1[0][1] + " " + matrix1[0][2] + "     " + matrix2[0][0] + " " + matrix2[0][1] + " " + matrix2[0][2] + "     " + answers[0][0] + " " + answers[0][1] + " " + answers[0][2]);
System.out.println(matrix1[1][0] + " " + matrix1[1][1] + " " + matrix1[1][2] + "  *  " + matrix2[1][0] + " " + matrix2[1][1] + " " + matrix2[1][2] + "  =  " + answers[1][0] + " " + answers[1][1] + " " + answers[1][2]);
System.out.println(matrix1[2][0] + " " + matrix1[2][1] + " " + matrix1[2][2] + "     " + matrix2[2][0] + " " + matrix2[2][1] + " " + matrix2[2][2] + "     " + answers[2][0] + " " + answers[2][1] + " " + answers[2][2]);
}

public static double[][] multiplyMatrix(double[][] a, double[][] b)
{
double[][] answers = new double[a.length][b[0].length];
for(int i = 0; i < answers.length; i++)
for(int j = 0; j < answers[i].length; j++)
for(int k = 0; k < b.length; k++)
answers[i][j] += a[i][k] * b[k][j];

return answers;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: