lost_in_the_source
lost_in_the_source

Reputation: 11237

How to multiply all elements in an doubles 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)];
}

Upvotes: 12

Views: 26960

Answers (2)

Christian Fries
Christian Fries

Reputation: 16932

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

Upvotes: 2

p.s.w.g
p.s.w.g

Reputation: 149020

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

Upvotes: 27

Related Questions