C#:将数组元素相互相乘

时间:2014-02-03 12:45:23

标签: c# c#-4.0

我希望能够将给定数值数组的所有成员相互相乘。

例如对于像[1,2,3,4]这样的数组,我想得到1*2*3*4的乘积。

我试过这个但是没有用:

/// <summary>
/// Multiplies numbers and returns the product as rounded to the nearest 2 decimal places.
/// </summary>
/// <param name="decimals"></param>
/// <returns></returns>
public static decimal MultiplyDecimals(params decimal[] decimals)
{
   decimal product = 0;

   foreach (var @decimal in decimals)
   {
       product *= @decimal;
   }

   decimal roundProduct = Math.Round(product, 2);
   return roundProduct;
}

对不起我知道这一定很简单!

感谢。

4 个答案:

答案 0 :(得分:8)

展示LINQ力量的另一个机会:

public static decimal MultiplyDecimals(params decimal[] decimals)
{
    return decimals.Aggregate(1m, (p, d) => p * d);
}

  • 1的初始值开头(m修饰符将常量静态类型为decimal),然后
  • 迭代地将所有值相乘。

编辑:这是一个包含舍入的变体。我省略了它,因为我不认为它是必需的(你没有decimal的浮点问题),但这里是为了完整性:

public static decimal MultiplyDecimals(params decimal[] decimals)
{
    return Math.Round(decimals.Aggregate(1m, (p, d) => p * d), 2);
}

答案 1 :(得分:2)

检查一下;

public static decimal MultiplyDecimals(params decimal[] decimals)
{
    decimal product = 1; // here is difference!

    foreach (var @decimal in decimals)
    {
        product *= @decimal;
    }
    decimal roundProduct = Math.Round(product, 2);
    return roundProduct;
}

答案 2 :(得分:2)

您必须将产品十进制的值设置为1或更高,因为x * 0每次都是0

- &GT; decimal product = 1;

答案 3 :(得分:1)

改变这个:

decimal product = 0;

到此:

decimal product = 1;

你开始乘以0就是这个原因。

相关问题