C++ 二维数组打印出元素的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21087186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
2D array print out sum of elements
提问by user1582575
I writing a program that sum of elements in a 2D array and print out the sum.
我编写了一个程序,将二维数组中的元素相加并打印出总和。
Here my code so far:
到目前为止,我的代码是:
#include <iostream>
#include <stdio.h>
int main()
{
int array [3][5] =
{
{ 1, 2, 3, 4, 5, }, // row 0
{ 6, 7, 8, 9, 10, }, // row 1
{ 11, 12, 13, 14, 15 } // row 2
};
int i, j=0;
int num_elements=0;
float sum=0;
for (i=0; i<num_elements; i++)
{
sum = sum + array[i][j];
}
/*for(i=0; i<num_elements; i++)
{
printf("%d ", array[i][j]);
}*/
// printf("a[%d][%d] = %d\n", sum);
// output each array element's value
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 5; j++ )
{
printf("a[%d][%d] = %d\n", i,j, array[i][j]);
}
}
system("PAUSE");
return 0;
}
I can print out the elements in each array fine. But I want to print out the sum of elements. I tried one as you can see in the comment section but it didn't work. Can anyone help?
我可以很好地打印出每个数组中的元素。但我想打印出元素的总和。正如您在评论部分看到的那样,我尝试了一个,但没有用。任何人都可以帮忙吗?
回答by Manos Ikonomakis
You are summing only the first column of your matrix:
您只对矩阵的第一列求和:
sum = sum + array[i][j];
where j is set to 0.
其中 j 设置为 0。
use a double loop:
使用双循环:
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 5; j++ )
{
sum+=array[i][j];
}
}
回答by Chowlett
This loop's the problem:
这个循环的问题:
int i, j=0;
int num_elements=0;
float sum=0;
for (i=0; i<num_elements; i++)
{
sum = sum + array[i][j];
}
It won't execute at all, since i<num_elements
is never true - num_elements
is 0. On top of which, you don't ever set j
away from 0.
它根本不会执行,因为i<num_elements
它永远不会是真的 -num_elements
是 0。最重要的是,你永远不会j
离开 0。
You need a double loop, like you use later on:
您需要一个双循环,就像您稍后使用的那样:
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 5; j++ )
{
sum += array[i][j];
}
}
回答by Hashim Khan
Try this to sum of all elements in 2D array-
试试这个对二维数组中所有元素的总和 -
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 5; j++ )
{
sum=sum+array[i][j];
}
}
回答by SoulRayder
First of all, you have initialized num_elements as zero. So you wont get anything.
首先,您已将 num_elements 初始化为零。所以你不会得到任何东西。
Also, for this,
另外,为此,
You need a double loop to print sum of allelements. Also declare additional variables such as row_num(for number of rows) and element_numfor number of elements in eachrow, and then use this code.
您需要一个双循环来打印所有元素的总和。还要声明额外的变量,例如row_num(用于行数)和element_num用于每行中的元素数,然后使用此代码。
for(i=0; i<row_num; i++)
{
for(j=0; j<element_num; j++)
{
sum = sum + array[i][j];
}
}
回答by Digital_Reality
As array stored in contiguous memory, it is possible to use only one loop.
由于数组存储在连续内存中,因此可以只使用一个循环。
for (int i=0; i<(3*5); i++) <-- 3*5 is num_of_colums*num_of_rows.
{
sum = sum + *(array[0]+i);
}