计算数组中两列的乘积然后计算总和C#

时间:2016-11-23 12:07:53

标签: c# arrays loops multidimensional-array

我有一个列数组,我需要为每列的2行产品的SUM。 例:   1 2 3 4    1 2 3 4    1 2 3 4    1 2 3 4 我想要做的是col2和col3的以下内容:   总数= 2 * 3 + 2 * 3 + 2 * 3 + 2 * 3 = 24 以下是此操作的代码: int product_col2Xcol3 = 0; int sum_totalcol2Xcol3 = 0; //计算col2和col3的SUM(Product) for(int row = 0; row< r; row ++) {     for(int j = 0; j< r; j ++)     {         product_col2Xcol3 = matrix [j,col2] * matrix [j,col3];         sum_totalcol2Xcol3 = sum_totalcol2Xcol3 + product_col2Xcol3;     } } Console.WriteLine(“Total is:”+ 2 * sum_totalcol2Xcol3); 我得到了一个结果,但答案是错误的,这是一个非常大的数字。请帮忙。谢谢!

3 个答案:

答案 0 :(得分:2)

for(int j = 0; j< r; j ++)有什么作用?你正在计算矩阵[j,col2] *矩阵[j,col3] * r次

int sum_totalcol2Xcol3 = 0;

for (int row = 0; row < r; row++)
{
    sum_totalcol2Xcol3 += matrix[row, col2] * matrix[row, col3];
}
Console.WriteLine("Total is :" + sum_totalcol2Xcol3 );

{{1}}

答案 1 :(得分:1)

int product_col2Xcol3 = 0;
int sum_totalcol2Xcol3 = 0;

//Calculations of the SUM(Product) of col2 and col3
for (int row = 0; row < number_of_rows; row++)
{

     product_col2Xcol3 = matrix[row, col2] * matrix[row, col3];
     sum_totalcol2Xcol3 = sum_totalcol2Xcol3 + product_col2Xcol3 ;

}
Console.WriteLine("Total is :" + sum_totalcol2Xcol3 );

答案 2 :(得分:1)

  int[,] matrix={
                    {1, 2, 3, 4},
                    {1, 2, 3, 4},
                    {1, 2, 3, 4},
                    {1, 2, 3, 4}
                };


  int product_col2Xcol3 = 0;
  int sum_totalcol2Xcol3 = 0;

  // if you precisely want the column 1 and 2 of each row then do as below:
  for (int row = 0; row <matrix.GetLength(0); row++)
  {

      product_col2Xcol3 = matrix[row, 1] * matrix[row, 2];
      sum_totalcol2Xcol3 += product_col2Xcol3;

  }
  Console.WriteLine("Total is :" + sum_totalcol2Xcol3);