如何对矩阵中的一行求和 [英] How to sum a row in a matrix

查看:87
本文介绍了如何对矩阵中的一行求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写方法:

public int sumRow(int[][] matrix, int row)

将2D数组中称为矩阵的行 row 求和.

that sums row row in the 2D array called matrix.

给出:

public void run()
{
    System.out.println(sumRow(new int[][]{{70,93,68,78,83},{68,89,91,93,72},{98,68,69,79,88}}, 2));
    System.out.println(sumRow(new int[][]{{1,1,1}, {2,2,2}, {3,3,3}}, 0));
    System.out.println(sumRow(new int[][]{{2,4,6,8,10}, {1,2,3,4,5}, {10,20,30,40,50}}, 2));
}

到目前为止,我有:

public int sumRow(int[][] matrix, int row)
{
    int sum = 0;
    for(int i = 0; i < matrix.length; i++)
    {
        for(int j = 0; j < matrix.length; j++)
        {
            sum = sum + matrix[j][i];
        }   
    }
    return sum;
}

我得到的输出分别是714、18和78,而应该分别是402、3和150.我在做什么错了?

The outputs I get are 714, 18, and 78 when they should be 402, 3, and 150. What am I doing wrong?

推荐答案

当您被要求对2D数组中的特定行求和时,您正在尝试对2D数组中的所有元素求和.在这种情况下,只需要一个for循环就可以遍历单行,就像遍历单个数组一样.循环将从第一个元素 matrix [row] [0] 开始,直到最后一个元素 matrix [row] [matrix [row] .length-1] ,因为 matrix [row] .length 是该矩阵特定行中的列/元素数.因此, matrix [row] .length-1 将是 matrix [row] 中最后一个元素的索引.这就是它的样子,

You're currently trying to sum all of the elements in the 2D array when you were asked to sum a specific row within the 2D array. In this case, you only need one for loop to traverse a single row like you would traverse a single array. The loop would start at the first element, matrix[row][0] and run until the last element, matrix[row][matrix[row].length - 1] since matrix[row].length is the number of columns/elements in that specific row of the matrix. Therefore, matrix[row].length - 1 would be the index of the last element in matrix[row]. Here's what it should look like,

public int sumRow(int[][] matrix, int row)
{
    int sum = 0;
    for(int i = 0; i < matrix[row].length; i++)
    {
        sum += matrix[row][i];
    }
    return sum;
}

这篇关于如何对矩阵中的一行求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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