【问题标题】:Calculate the product of two columns in an array then the sum C#计算数组中两列的乘积,然后求和 C#
【发布时间】:2017-04-07 10:40:29
【问题描述】:

我有一个包含列的数组,我需要对 2 列的每行乘积求和。

示例:

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;

//Calculations of the SUM(Product) of col2 and col3
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 );

我得到了一个结果,但答案是错误的,它是一个非常大的数字。请帮忙。谢谢!

【问题讨论】:

  • for (int j = 0; j &lt; r; j++) 有什么作用?您正在计算 matrix[j, col2] * matrix[j, col3] * r 次。
  • 这似乎是它正在做的问题 * r 最后这就是为什么我得到这么大的数字......如何处理它?
  • 你为什么要做 *r ,根据你的例子,它不需要,而且你正在做额外的循环,这就是为什么你会得到巨大的数字。
  • @Johnny 请回滚您的编辑并发布之前的代码。现在这篇文章有一个没有问题的公认答案。这对任何人都没有帮助

标签: c# arrays loops multidimensional-array


【解决方案1】:

for (int j = 0; j

int product_col2Xcol3 = 0;
int sum_totalcol2Xcol3 = 0;

//Calculations of the SUM(Product) of col2 and col3
for (int row = 0; row < r; row++)
{
    product_col2Xcol3 = matrix[row, col2] * matrix[row, col3];
    sum_totalcol2Xcol3 = sum_totalcol2Xcol3 + product_col2Xcol3 ;
}

// why 2* ?????? think it shouldn't be there.
Console.WriteLine("Total is :" + 2*sum_totalcol2Xcol3 );

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 );

【讨论】:

  • 看到了,你可能注意到这是一个错字?
  • 感谢您突出显示 j 部分!像魅力一样工作
【解决方案2】:
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 );

【讨论】:

    【解决方案3】:
      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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 2016-10-12
      • 1970-01-01
      相关资源
      最近更新 更多