首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使矩阵形式发生变化?

如何使矩阵形式发生变化?
EN

Stack Overflow用户
提问于 2021-05-13 09:53:01
回答 1查看 39关注 0票数 0

如何改变矩阵形式的结果?

这个代码中有什么错误?

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

发布于 2021-05-13 13:45:07

我不太明白你的问题。要在新行上输出结果数组的每一行吗?还是应该用逗号隔开?

要打印换行符中的每一行:

代码语言:javascript
复制
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();
}

要在行之间打印逗号,请执行以下操作:

代码语言:javascript
复制
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(", ");
}

如果这不是解决方案,请详细说明您的问题以获得更多信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67517191

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档