Java问题,从键盘输入一个M*N的矩阵,并对这个矩阵进行转置操作,就是将aij 与 aji 内容互转(检查问题)
packagecom.homework.fourdays;importjava.util.Scanner;publicclasspage81_question02{pub...
package com.homework.fourdays;
import java.util.Scanner;
public class page81_question02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m ,n ,x ;
System.out.println("请输入矩阵M*N中的M值");
m = in.nextInt();
System.out.println("请输入矩阵M*N中的N值");
n = in.nextInt();
int[][] a = new int[m][n];
System.out.println("请输入" + m + " * " + n + "矩阵中的所有元素");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
System.out.print(a[i][j] + " ");
}
System.out.println("");
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
x = a[j][i];
a[j][i] = a[i][j];
a[i][j] = x;
}
}
System.out.println("转置结果");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println("");
}
}
}
这段代码没法完成转置操作,输出还是同样矩阵,解决问题有追加悬赏。 展开
import java.util.Scanner;
public class page81_question02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m ,n ,x ;
System.out.println("请输入矩阵M*N中的M值");
m = in.nextInt();
System.out.println("请输入矩阵M*N中的N值");
n = in.nextInt();
int[][] a = new int[m][n];
System.out.println("请输入" + m + " * " + n + "矩阵中的所有元素");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = in.nextInt();
System.out.print(a[i][j] + " ");
}
System.out.println("");
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
x = a[j][i];
a[j][i] = a[i][j];
a[i][j] = x;
}
}
System.out.println("转置结果");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println("");
}
}
}
这段代码没法完成转置操作,输出还是同样矩阵,解决问题有追加悬赏。 展开
1个回答
展开全部
修改后的Java程序:
package com.homework.fourdays;
import java.util.Scanner;
public class page81_question02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m, n;
int i, j;
System.out.println("请输入矩阵M*N中的M值");
m = in.nextInt();
System.out.println("请输入矩阵M*N中的N值");
n = in.nextInt();
int[][] a = new int[m][n]; //存储转置前的矩阵
int[][] b = new int[n][m]; //存储转置后的矩阵
System.out.println("请输入" + m + " * " + n + "矩阵中的所有元素");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
a[i][j] = in.nextInt();
}
}
//矩阵转置
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
b[j][i] = a[i][j];
}
}
System.out.println("转置前");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
System.out.printf("%6d", a[i][j]);
}
System.out.println();
}
System.out.println("转置后");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.printf("%6d", b[i][j]);
}
System.out.println();
}
}
}
运行测试:
请输入矩阵M*N中的M值
2
请输入矩阵M*N中的N值
3
请输入2 * 3矩阵中的所有元素
1 2 3
4 5 6
转置前
1 2 3
4 5 6
转置后
1 4
2 5
3 6
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询