``````Hi, i need help creating a fuel volume calculator to estimate the gallons of fuel
required to travel 5 distances

so far the 5 distances in miles the user enters are stored in an array,
however i need a sum to find the average of the five numbers

here is the code:

<!DOCTYPE html
<html
<body>
<h1>Referred Portfolio Part 1</h1>
<title>Referred Portfolio Part 1</title>
<src="javascript.js"></script>
<script>
var name = window.prompt("What is your name?")
var fuel = window.prompt("Please enter your car's fuel consumption in miles per gallon")
var distance,miles = [];
var sum = 0;
for(var i = 0; i < 5; i++){
distance = window.prompt("Please enter distance in miles");
miles.push(distance);
}
console.log(miles);

document.write("Fuel calculation for "+name + "<br />Fuel consumption: " + fuel + "<br />Average distance travelled: "+distance);
</script>

</body>
</html>
``````
2
Contributors
4
Replies
59
Views
3 Years
Discussion Span
Last Post by mehul12345

An average is just the total sum of the elements divided by the number of elements. increment your sum variable by the entered value inside the loop and then, once the loop is finished divide it by 5.

so what would i need to enter to work out the average of random user entered numbers?

Sum the values held in distance, seeng as that contains the values entered, and divide it by the number of elements.

this is what i have so far, its adding up the values but if i enter a number over 5 it doesn't work (line 13)

``````<!DOCTYPE html
<html
<body>
<h1>Referred Portfolio Part 1</h1>
<title>Referred Portfolio Part 1</title>
<script src="javascript.js"></script>,
<script>
var name = window.prompt("What is your name?")
var fuel = window.prompt("Please enter your car's fuel consumption in miles per gallon")
var average = 0;
var sum = 0;
for (distance = 1; distance <=5; distance++)
{
sum += distance;
distance = window.prompt("Please enter distance in miles");
console.log(distance);

}

document.write("Fuel calculation for "+name + "<br />Fuel consumption: " + fuel + " Miles per gallon " + "<br />Average distance travelled: "+sum + " Miles ");
</script>