[英]How do i store the value of sum in the new array b
public class HW9P1
{
public static void main(String[] args)
{
/*int[][] a1 = { { 4, -2, 10 },
{ 19, 3, -5 } };
int[] b1 = coloumnsum(a1);*/
int[][] a2 = { { 7, -10 },
{ 4, 13 },
{ 1, 0 } };
int[] b2 = coloumnsum(a2);
int i,j;
for (i=0; i<b2.length; i++)
{
System.out.print(b2[i] + " ");
}
}
public static int[] coloumnsum (int[][] a)
{
int[] b = new int[a[0].length];
int i,j, sum= 7;
for (j=0; j<a[0].length; j++)
{
for (i=0; i<a.length; i++)
{
sum = sum + a[i][j];
}
}
return b;
}
}
I have this code so far, which gives me the sum from the columns.Takes and 2d array and return 1d array. 到目前为止,我已经有了这段代码,这给了我来自column.Takes和2d数组并返回1d数组的总和。 when i run this code, i get two 00 For ex {2,4} {1,9} sum should be {3,13}
当我运行此代码时,我得到两个00,对于前{2,4} {1,9},总和应为{3,13}
You aren't storing your sum
back into the array b
. 您没有将
sum
存储回数组b
。 You actually don't need sum
, just add the values directly in the array. 实际上,您不需要
sum
,只需将值直接添加到数组中即可。 Like, 喜欢,
public static int[] coloumnsum(int[][] a) {
int[] b = new int[a[0].length];
for (int j = 0; j < a[0].length; j++) {
for (int i = 0; i < a.length; i++) {
b[j] += a[i][j];
}
}
return b;
}
When I make that change your current code produces (as expected) 当我进行更改时,您当前的代码会产生(按预期)
12 3
7
if all you want is to sum the columns of the 2D array. 7
开始求和。 b
. b
分配任何东西。 below illustrates the correct approach to sum the columns: 下面说明了汇总列的正确方法:
public static int[] coloumnsum (int[][] a)
{
int[] b = new int[a[0].length];
for (int i = 0; i < a[0].length; i++){
for (int j = 0; j < a.length; j++)
b[i] += a[j][i];
}
return b;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.