将二维数组中每列的所有元素相加 [英] Adding up all the elements of each column in a 2D array

查看:143
本文介绍了将二维数组中每列的所有元素相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个虚拟的二维数组:

So I have this dummy 2D array:

int mat[][] = {
        {10, 20, 30, 40, 50, 60, 70, 80, 90},
        {15, 25, 35, 45},
        {27, 29, 37, 48},
        {32, 33, 39, 50, 51, 89}};

我想按列将所有值相加,以便添加 10 + 15 + 27 + 32 并返回 84 等等.到目前为止,我有这个:

I want to add up all the values by columns so it would add 10 + 15 + 27 + 32 and return 84 and so on. I have this so far:

public void sum(int[][] array) {
    int count = 0;
    for (int rows = 0; rows < array.length; rows++) {
        for (int columns = 0; columns < array[rows].length; columns++) {
            System.out.print(array[rows][columns] + "\t");
            count += array[0][0];
        }
        System.out.println();
        System.out.println("total = " + count);
    }
}

有人可以帮忙吗?另外 System.out.print(array[rows][columns] + "\t"); 将数组按行打印出来,有没有办法按列打印出来?>

Can anyone help with this? Also the System.out.print(array[rows][columns] + "\t" ); prints the array out by rows, is there a way to print it out by columns?

推荐答案

一种可能的解决方案是首先找到所有子数组的最大大小,然后多次迭代以找到每列的总和,避免不可用的值.

One possible Solution would be to first find maximum size of all sub arrays and iterate that many times to find sum of each column avoiding unavailable values.

public static void main(String[] args) {
    int mat[][] = {{10, 20, 30, 40, 50, 60, 70, 80, 90},
            {15, 25, 35, 45},
            {27, 29, 37, 48},
            {32, 33, 39, 50, 51, 89},
    };

    // Find maximum possible length of sub array
    int maxLength = 0;
    for (int i = 0; i < mat.length; i++) {
        if (maxLength < mat[i].length)
            maxLength = mat[i].length;
    }

    for (int i = 0; i < maxLength; i++) {
        int sum = 0;
        for (int j = 0; j < mat.length; j++) {
            // Avoid if no value available for
            // ith column from this subarray
            if (i < mat[j].length)
                sum += mat[j][i];
        }
        System.out.println("Sum of Column " + i + " = " + sum);
    }
}

这篇关于将二维数组中每列的所有元素相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆