如何改变矩阵形式的结果?
这个代码中有什么错误?
package arrays;
import java.util.Scanner;
public class MatrixAddition {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Dimension : ");
int rows = sc.nextInt();
int cols = sc.nextInt();
int a[][] = new int[rows][cols];
int b[][] = new int[rows][cols];
System.out.println("Enter array a");
for(int i = 0; i<rows;i++) {
for(int j = 0; j<cols ; j++) {
a[i][j] = sc.nextInt();
}
}
System.out.println("Enter array b");
for(int i = 0; i<rows;i++) {
for(int j = 0; j<cols ; j++) {
b[i][j] = sc.nextInt();
}
}
int c[][] = new int[rows][cols];
for(int i = 0; i<rows;i++) {
for(int j = 0; j<cols ; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("result array c is: ");
for(int i = 0; i<rows;i++) {
for(int j = 0; j<cols ; j++) {
System.out.print(c[i][j] +" ");
}
}
System.out.println();
}
}输入维数:
2 3
输入数组a
2 3 4
5-2 -1
输入数组b
7 8 9
-5 -7 -5
结果数组c是:
9 11 13 0 -9 -6
发布于 2021-05-13 13:45:07
我不太明白你的问题。要在新行上输出结果数组的每一行吗?还是应该用逗号隔开?
要打印换行符中的每一行:
System.out.println("result array c is: ");
for(int i = 0; i<rows;i++) {
for(int j = 0; j<cols ; j++) {
System.out.print(c[i][j] +" ");
}
// all columns of a row printed, begin a new line
System.out.println();
}要在行之间打印逗号,请执行以下操作:
System.out.println("result array c is: ");
for(int i = 0; i<rows;i++) {
for(int j = 0; j<cols ; j++) {
System.out.print(c[i][j] +" ");
}
// all columns of a row printed, insert a comma
System.out.print(", ");
}如果这不是解决方案,请详细说明您的问题以获得更多信息。
https://stackoverflow.com/questions/67517191
复制相似问题