t_plusplus
t_plusplus

Reputation: 4209

C#: Multiply an array elements with each other

I would like to be able to multiply all members of a given numeric array with each other.

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

I have tried this but didn't 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 am sorry I know this must be simple!

Thanks.

Upvotes: 4

Views: 1195

Answers (4)

Heinzi
Heinzi

Reputation: 172478

Another opportunity to show off the power of LINQ:

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

This

  • starts with an initial value of 1 (the m modifier statically types the constant as decimal) and then
  • iteratively multiplies all the values.

EDIT: Here a variant that includes rounding. I've omitted it, because I don't think it's required (you don't have floating-point problems with decimal), but here it is for completeness:

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

Upvotes: 8

brothers28
brothers28

Reputation: 1206

You have to set the value of the product decimal to 1 or higher because x * 0 everytime is 0

--> decimal product = 1;

Upvotes: 2

AymenDaoudi
AymenDaoudi

Reputation: 8309

Change this :

decimal product = 0;

to this :

decimal product = 1;

You started multiplying by 0 that's why.

Upvotes: 1

pankeel
pankeel

Reputation: 1148

check this;

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

Upvotes: 2

Related Questions