C #: multiply array elements by each other

I would like to be able to multiply all the members of a given number array by each other.

So, for example, for an array like:, [1,2,3,4]I would like to get a product 1*2*3*4.

I tried this but did not work:

/// <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;
}

I'm sorry that I know this should be easy!

Thanks.

+4
source share
4 answers

Another opportunity to demonstrate the power of LINQ:

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

it

  • starts with the initial value 1(the modifier mstatically enters the constant as decimal), and then
  • iteratively multiplies all values.

EDIT: , . , , ( decimal), :

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

;

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

You must set the decimal value of the product to 1 or higher, because x * 0 each time is 0

-> decimal product = 1;

+2
source

Change this:

decimal product = 0;

:

decimal product = 1;

You started to multiply by 0, why.

+1
source

Source: https://habr.com/ru/post/1525047/


All Articles