Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply all elements in an doubles list?

Tags:

c#

list

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)];
}
like image 620
Edward Karak Avatar asked Oct 12 '13 15:10

Edward Karak


2 Answers

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);
like image 112
p.s.w.g Avatar answered Oct 18 '22 20:10

p.s.w.g


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];
}
like image 45
Christian Fries Avatar answered Oct 18 '22 19:10

Christian Fries