SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
Procedural Abstraction And Functions That Return A Value
Exercise:
Programming Projects
Question:2 | ISBN:9780321531346 | Edition: 7

Question

Modify your program from Programming Project 1 so that it will take input data for two cars and output the number of miles per gallon deliv-ered by each car. Your program will also announce which car has the best fuel efficiency (highest number of miles per gallon).

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program: 

#include<iostream>  
using namespace std;
#define LITERPERGALLON (3.785)

double mpg(double m,double l)
{
	return (m*LITERPERGALLON/l);
}
void main()
{
	double fliters,fmiles,sliters,smiles,fmpg,smpg;
	char choice;
	do
	{ 
		cout<<"Enter miles traveled by first car"<<endl;
		cin>>fmiles;

		cout<<"Enter liters gasoline:"<<endl;
		cin>>fliters;

		cout<<"Enter miles traveled by second car"
			<<endl;
		cin>>smiles;

		cout<<"Enter in liters gasoline:"<<endl;
		cin>>sliters;

		if (fliters == 0 || sliters == 0)
			cout<<"\n Invalid input";
		else
		{
			fmpg = mpg (fmiles,fliters);	
			smpg = mpg (smiles,sliters);    

			cout<<"Miles per gallon "<<fmpg<<endl;
			cout<<"Miles per gallon "<<smpg<<endl;
		}
		if(fmpg == smpg) 
		{
			cout<<"Both cars are best."<<endl;
		}
		else if(fmpg > smpg)
		{
			cout<<"First car is best."<<endl;
		}

		else 
			cout<<"Second car is best."<<endl;             

		cout<<"To continue then enter 'Y' or 'y'"<<endl;
		cin>>choice;

	} while(choice =='y'|| choice =='Y');

}

Output:

Enter miles traveled by first car
1000
Enter liters gasoline:
500
Enter miles traveled by second car
2000
Enter in liters gasoline:
200
Miles per gallon 7.57
Miles per gallon 37.85
Second car is best.
To continue then enter 'Y' or 'y'
n

 

0 0

Discussions

Post the discussion to improve the above solution.