如何获得二维数组中行和列的总和? [英] How do I get the sum of rows and columns in 2 dimensional array?

查看:284
本文介绍了如何获得二维数组中行和列的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的错误代码

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 to cs 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


这篇关于如何获得二维数组中行和列的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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