How do I multiply the contents of a list <double>
?
List<double> mult=new List<double>{3, 5, 10};
So far I have:
double r=0.0;
for(int i=0;i<mult.Count;i++)
{
r=mult[i]*mult[(i+1)];
}
To fix your loop, start with 1.0
and multiply each item in the list, like this:
double r = 1.0;
for(int i = 0; i < mult.Count; i++)
{
r = r * mult[i]; // or equivalently r *= mult[i];
}
But for simplicity, you could use a little Linq with the Aggregate
extension method:
double r = mult.Aggregate((a, x) => a * x);
What do you mean by multiply? If you like to calculate the product, then your code is wrong and the correct code is
double r=1.0;
for(int i=0;i<mult.Count;i++)
{
r *= mult[i];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With