You have 3 issues in your code:
- You start the loop at index 1, but index 1 will be skipped due to the
if (i%2 == 0)
, so essentially the loop starts at 2. So, change the condition to if (i%2 == 1)
.
- To get an average, you need to sum up two numbers, then divide it by 2. You use one number and add the half of the second one. Use braces to fix that:
(x[i] + x[i - 1]) / 2
.
- You use an integer division but expect a double result. Fix that by dividing through
2.0
instead of 2
: (x[i] + x[i - 1]) / 2.0
Full code:
var x = new List<int>{28, 19, 24, 50, 29, 43};
List<double> avg = new List<double>();
for(int i = 1; i < x.Count(); i++)
{
if(i%2 == 1)
{
double D = (x[i] + x[i - 1]) / 2.0;
avg.Add(D);
}
}
However, the code seems too complex. If you read that again in a few months you'll probably not understand it any more.
IMHO
- it would be better to start at index 0, because that's the usual way to process all numbers of an array.
- instead of weird modulo operation, just walk in steps of 2.
- Change the name of the variables.
- Add some precondition check if averaging is possible
var pairs = new List<int>{28, 19, 24, 50, 29, 43};
List<double> averages = new List<double>();
if (pairs.Count() %2 != 0) throw new ArgumentException("Can't build averages on that list. The list needs to have an even number of elements.");
for(int i = 0; i < pairs.Count() - 1; i+=2)
{
double average = (pairs[i] + pairs[i + 1]) / 2.0;
averages.Add(average);
}