Reputation: 4209
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
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
1
(the m
modifier statically types the constant as decimal
) and thenEDIT: 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
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
Reputation: 8309
Change this :
decimal product = 0;
to this :
decimal product = 1;
You started multiplying by 0 that's why.
Upvotes: 1
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