In: Computer Science
perform each of the following steps:
a) Read the problem statement.
b) Formulate the algorithm using pseudocode and top-down, stepwise refinement.
c) Define the algorithm in JavaScript.
d) Test, debug and execute the JavaScript.
e) Process three complete sets of data.
Drivers are concerned with the mileage obtained by their automobiles. One driver has kept track of several tankfuls of gasoline by recording the number of miles driven and the number of gallons used for each tankful. Develop a script that will take as input the miles were driven and gallons used (both as integers) for each tankful. The script should calculate and output HTML5 text that displays the number of miles per gallon obtained for each tankful and prints the combined number of miles per gallon obtained for all tankfuls up to this point. Use prompt dialogs to obtain the data from the user.
Algorithm:
1.Start
2.Declare 2 variable totalMiles ,gallons
3.Take user input for the two variables
4.Calculate mpg using the formula totalMiles/gallons
5.Return the value of mpg
<!DOCTYPE html>
<html>
<head>
<title>Miles per Gallon</title>
<meta charset="UTF-8" />
<script type="text/javascript">
function calcMPG() {
var totalMiles = document.forms[0].totalMileage.value;
var gallons = document.forms[0].gallonsUsed.value;
if (isNaN(totalMiles) || isNaN(gallons)) {
window.alert("Each textbox must contain only numbers!");
} else {
if (gallons > 0) {
document.forms[0].milesPerGallon.value = (
totalMiles / gallons
).toFixed(1);
}
}
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("<p><h2>Miles Per Gallon Calculator</h2></p>");
document.write(
"<p><h5>To find miles per gallon, enter total miles travelled and gallons of gas used.</h5></p>"
);
</script>
<form action="">
<p>
Miles:
<input
type="text"
name="totalMileage"
value="0"
size="10"
onchange="calcMPG()"
/>
</p>
<p>
Gallons Used:
<input
type="text"
name="gallonsUsed"
value="0"
size="10"
onchange="calcMPG()"
/>
</p>
<p>
Miles Per Gallon:
<input type="text" name="milesPerGallon" value="0" size="10" />
</p>
</form>
</body>
</html>