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

t_p*_*lus 4 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;
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

Hei*_*nzi 8

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

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

这个

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

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

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