如何获得二维数组中行和列的总和?
问题描述:
这是我的错误代码
Here''s my incorrect code
cout<<"The numbers are"<<endl;
for(r=0; r<rn; r++)
{
cout<<endl;
for(c=0; c<cn; c++)
{
cout<<a[r][c]<<"\t";
}
}
for(r=0; r<rn; r++)//my code for getting the sum of 2d array
{
for(c=0; c<cn; c++)
{
cs=cs+a[r][c];
}
cout<<cs<<" ";//but the output is incorrect
}
}
这应该是输出
This should be the output
Enter number of columns: 4
Enter number of rows: 3
Enter twelve numbers: 1 1 1 1 1 1 1 1 1 1 1 1
The numbers are:
1 1 1 1
1 1 1 1
1 1 1 1
Sum of number 1 column is: 3
Sum of number 2 column is: 3
Sum of number 3 column is: 3
Sum of number 4 column is: 3
Sum of number 1 row is: 4
Sum of number 2 row is: 4
Sum of number 3 row is: 4
像这样的先生,但列的总和仅显示一个答案...
Like this sir but the sum of the columns displays only one answer...
for(r=0; r<rn; r++)
{
cs = 0;
for(c=0; c<cn; c++)
{
cs=cs+a[r][c];
}
cout<<"Sum of number "<<r<<" row is"<<cs<<endl;
}
cout<<"Sum of number "<<c<<" column is"<<cs<<endl;//displays only one answer
答
好吧……您不知道"不要说您得到什么值,但是我建议您从开始对列求和之前重置计数器的值开始.
此刻,您只是不断地添加到cs
!
Well...You don''t say what values you get, but I''d suggest that place to start would be by resetting the value of your counter before you start summing the columns...
At the moment, you are just adding tocs
continually!
for(r=0; r<rn; r++)
{
cs = 0; // *** ADD THIS ***
for(c=0; c<cn; c++)
{
cs=cs+a[r][c];
}
cout<<cs<<" ";
}
然后,在可行的情况下,添加第二对循环,循环执行内部行和外部列.
Then, when that works, add a second pair of loops which do the rows on the inside and the columns on the outside.
就像这个先生,但是列的总和仅显示一个答案...
Like this sir but the sum of the columns displays only one answer...
for(r=0; r<rn; r++)
{
cs = 0;
for(c=0; c<cn; c++)
{
cs=cs+a[r][c];
}
cout<<"Sum of number "<<r<<" row is"<<cs<<endl;
}
cout<<"Sum of number "<<c<<" column is"<<cs<<endl;//displays only one answer