《Java语言程序设计(基础篇)》(第10版梁勇著)第八章练习题答案
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
《Java语言程序设计(基础篇)》(第10版梁勇著)第八章
练习题答案
《Java语言程序设计(基础篇)》(第10版梁勇著)
第八章练习题答案
8.1
public class Exercise08_01 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a 3 by 4 matrix row by row: ");
double[][] m = new double[3][4];
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[i].length; j++)
m[i][j] = input.nextDouble();
for (int j = 0; j < m[2].length; j++) {
System.out.println("Sum of the elements at column " + j + " is " + sumColumn(m, j));
}
}
public static double sumColumn(double[][] m, int columnIndex) {
double total = 0;
for (int i = 0; i < m.length; i++)
total += m[i][columnIndex];
return total;
}
}
8.1附加
public class Exercise08_01Extra {
public static void main(String[] args) {
final int N = 2;
Scanner input = new Scanner(System.in);
double[][] A = new double[N][N];
System.out.print("Enter a, b, c, d: ");
A[0][0] = input.nextDouble();
A[0][1] = input.nextDouble();
A[1][0] = input.nextDouble();
A[1][1] = input.nextDouble();
double[][] inverseA = inverse(A);
if (inverseA == null)
System.out.println("No inverse matrix");
else
printMatrix(inverse(A));
}
public static void printMatrix(double[][] A) {
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++)
System.out.print(A[i][j] + " ");
System.out.println();
}
}
public static double[][] inverse(double[][] A) {
double[][] result = new double[A.length][A.length]; double determinant = A[0][0] * A[1][1] - A[0][1] * A[1][0]; if (determinant == 0)
return null;
result[0][0] = A[1][1] / determinant;
result[0][1] = -A[0][1] / determinant;
result[1][0] = -A[1][0] / determinant;
result[1][1] = A[0][0] / determinant;
return result;
}
}
8.2
public class Exercise08_02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a 4 by 4 matrix row by row: ");
double[][] m = new double[4][4];
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
m[i][j] = input.nextDouble();
System.out.print("Sum of the elements in the major diagonal is "
+ sumMajorDiagonal(m));
}
public static double sumMajorDiagonal(double[][] m) {
double sum = 0;
for (int i = 0; i < m.length; i++)
sum += m[i][i];
return sum;
}
}
8.2附加
public class Exercise08_02Extra {
final static int N = 3;
public static void main(String[] args) {
double[][] A = new double[N][N];
System.out.print("Enter a11, a12, a13, a21, a22, a23, a31, a32, a33: ");