gpt4 book ai didi

java - 从行到列相加

转载 作者:行者123 更新时间:2023-12-01 15:02:48 25 4
gpt4 key购买 nike

此代码打印每行的总和......如何转换它以便打印每列的总和?谢谢,,

public class NewClass{
public static void main( String[] arg )
{
int[][] data =
{ { 1, 2},
{ 2, 2},
{ 1, 2, 4, 5},
{ 2, 2, 4,},
{ 1, 1, 4, 5 },
{ 2, 1, }};



for ( int row=0; row < data.length; row++)
{
int sum = 0;
for ( int col=0; col < data[row].length; col++)
{
sum = sum + data[row][col];
}
System.out.print("Sum of Row " + row+" is : ");
System.out.println( sum );
}
}
}

最佳答案

您必须考虑到每行中的列数不同。

首先,找到数据集中的最大列数,然后对各列求和。

public class NewClass {
public static void main(String[] arg) {
int[][] data = { { 1, 2 }, { 2, 2 }, { 1, 2, 4, 5 }, { 2, 2, 4, },
{ 1, 1, 4, 5 }, { 2, 1, } };

int maxColLength = 0;
for (int row = 0; row < data.length; row++) {
int colLength = data[row].length;
if (colLength > maxColLength) {
maxColLength = colLength;
}
}

for (int col = 0; col < maxColLength; col++) {
int sum = 0;
for (int row = 0; row < data.length; row++) {
if (col < data[row].length) {
sum = sum + data[row][col];
}
}
System.out.print("Sum of Column " + col + " is : ");
System.out.println(sum);
}
}
}

关于java - 从行到列相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13400936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com