Can anyone help me figure out what I am doing wrong when trying to get the sum and the average of the elements in the array? My assignment is: You are preparing for the Boston Marathon. In order to prepare, you need to train for 10 weeks, running an increasing number of miles per week, starting at running at least 2 miles your first week up to 26 miles by week 10. One question states to find the sum of the total miles ran over ten weeks and the average miles ran over the ten weeks, and what I have will execute without errors, but the sum is coming out as 26.000000000004 which I know is wrong. Any advice would be greatly appreciated. I am new to this.
public class arrayTest
{
public static void main(String[] args) {
double[] miles = new double [10];
double milesPerWeek = 26.0 / 10;
double totalMiles = 0;
double sum = 0;
double average = 0;
System.out.println("Week\tMiles");
for (int i = 0; i < miles.length; i++)
{
miles[i] += milesPerWeek;
totalMiles += miles[i];
System.out.println("Week " + i + " miles " + totalMiles);
}
for (int i = 0; i < miles.length; i++)
{
sum = sum + miles[i];
average = sum / miles.length;
}
System.out.print("the sum of the miles ran is: " + sum + "\n");
System.out.print("the average miles ran is: " + average);
}
}
The result reads:
Week Miles
Week 0 miles 2.6
Week 1 miles 5.2
Week 2 miles 7.800000000000001
Week 3 miles 10.4
Week 4 miles 13.0
Week 5 miles 15.6
Week 6 miles 18.2
Week 7 miles 20.8
Week 8 miles 23.400000000000002
Week 9 miles 26.000000000000004
the sum of the miles ran is: 26.000000000000004
the average miles ran is: 2.6000000000000005