58.3k views
2 votes
help users calculate their car miles per gallon. write a program to allow a user to enter the number of miles driven and the number of gallons of gas used. the output should be the miles per gallon. use a Do... while (post-test) loop to allow users to enter as many sets of data as desired.

User Ty Kayn
by
5.3k points

1 Answer

1 vote

Answer:

The c++ program for the scenario is given below.

#include <iostream>

using namespace std;

int main() {

float miles, gallon, speed;

char reply;

cout<<"This program calculates speed of your car in miles per gallon." <<endl;

do

{

do

{

cout<<endl<<"Enter the miles driven by your car" <<endl;

cin>>miles;

if(miles<=0)

{

cout<<"Invalid input. Enter the miles driven by your car."<<endl;

cin>>miles;

}

}while(miles<=0);

do

{

cout<<"Enter the gallons of gas used by your car" <<endl;

cin>>gallon;

if(gallon<=0)

{

cout<<"Invalid input. Enter the gallons of gas used by your car."<<endl;

cin>>gallon;

}

}while(gallon<=0);

speed = miles/gallon;

cout<<"Your car drives at "<<speed<<" miles per gallon."<<endl;

cout<<"Do you with to continue (y/n)?"<<endl;

cin>>reply;

}while(reply != 'n');

return 0;

}

This program calculates speed of your car in miles per gallon.

Enter the miles driven by your car

0

Invalid input. Enter the miles driven by your car.

-9

Enter the miles driven by your car

12.34

Enter the gallons of gas used by your car

0

Invalid input. Enter the gallons of gas used by your car.

-2

Enter the gallons of gas used by your car

3.4

Your car drives at 3.62941 miles per gallon.

Do you with to continue (y/n)?

n

Step-by-step explanation:

The do while loop is also known as post-test loop. This loop executes once mandatorily. After first execution, the condition is tested and based on the condition, the loop either executes again or discontinues.

In this program, the loop continues till the user wants to try out different sets of data for calculation. Once the user enters input to quit, the loop discontinues.

Do

{

cout<<"Do you with to continue (y/n)?"<<endl;

cin>>reply;

}while(reply != 'n');

Moreover, the input by the user is tested for validity. The input cannot be negative or zero. This is implemented by if statement.

if(miles<0)

{

cout<<"Invalid input. Miles cannot be negative."<<endl;

cin>>miles;

}

The same validity is implemented for gallons of gas also.

User Binoculars
by
5.8k points