Search code examples
htmlbbedit

I cant figure out quite how to write this program. I want to make the program ask the user for speed and time and use a loop to display total


function showAndCalculateDistance(speed, time) {

for (var i=0; i<5; i++){

var mph = vehicleSpeed* timeTraveled;

return mph

}

var vehicleSpeed = parseInt(prompt('How fast is the vehicle traveling (in miles per hour)? '));
var timeTraveled = parseFloat(prompt('How long has this vehicle traveled (in hours)? '));
var totalDistanceTraveled = showAndCalculateDistance(vehicleSpeed,timeTraveled);
alert('In ' + timeTraveled + ' hours, a vehicle traveling at ' + vehicleSpeed + ' miles/hour will have traveled ' + totalDistanceTraveled + ' miles.');

I want to write the program so it calls the function using a loop to display the number of miles the vehicle traveled for each hour of the time period, and returning the total number of miles traveled


Solution

  • You are missing a closing parenthesis to terminate your for loop. In the future, you should indent your code to make catching errors like this easier. Although I'm not sure what exactly the purpose of the for loop is in your code, since you are just assigning the same value to mph 5 times.

    function showAndCalculateDistance(speed, time) {
    
        for (var i=0; i<5; i++){
    
            var mph = vehicleSpeed* timeTraveled;
    
        }
    
        return mph
    
    } // <-- you did not put this.
    
    var vehicleSpeed = parseInt(prompt('How fast is the vehicle traveling (in miles per hour)? '));
    var timeTraveled = parseFloat(prompt('How long has this vehicle traveled (in hours)? '));
    var totalDistanceTraveled = showAndCalculateDistance(vehicleSpeed,timeTraveled);
    alert('In ' + timeTraveled + ' hours, a vehicle traveling at ' + vehicleSpeed + ' miles/hour will have traveled ' + totalDistanceTraveled + ' miles.');