// this program calculates the miles per gallon and total cost // of a car trip #include <iostream.h> #include <iomanip.h> // function prototypes float mpg(int,float); float tripcost(float,float,float); void heading(); int main() { int milesdriven; float costgallon; float costtolls; float gasused; float totalcost; // call the heading function heading(); // set up output to print float values with one decimal place cout << setiosflags(ios::fixed); cout << setiosflags(ios::showpoint); cout << setprecision(1); // prompt for the number of miles driven and the amount of gas used cout << "Enter the number of miles driven: "; cin >> milesdriven; cout << "Enter the gallons of gas used: "; cin >> gasused; // call the mpg function to calculate miles per gallon and print the // value returned cout << "On this trip you got " << mpg(milesdriven,gasused) << " miles per gallon.\n"; // prompt for the cost of a gallon of gas and the cost of tolls cout << "Enter the cost paid for a gallon of gas: "; cin >> costgallon; cout << "Enter the cost of tolls on the trip: "; cin >> costtolls; // change output to print floats with two decimal places cout << setprecision(2); // call totalcost to compute the cost of the trip, then print totalcost = tripcost(costgallon,gasused,costtolls); cout << "The total cost of the trip was " << totalcost << endl; } // print a heading in the output void heading() { cout << "Sample Program for Class Demonstration\n"; cout << "Calculate gas mileage and cost for a trip\n\n"; } // calculate and return the miles per gallon float mpg(int milesdriven,float gasused) { return milesdriven / gasused; } // calculate and return the cost of the trip (cost of gas + cost of tolls) float tripcost(float costgallon,float gasused,float costtolls) { return costgallon * gasused + costtolls; }
Sample Program for Class Demonstration Calculate gas mileage and cost for a trip Enter the number of miles driven: 128 Enter the gallons of gas used: 4.8 On this trip you got 26.7 miles per gallon. Enter the cost paid for a gallon of gas: 1.39 Enter the cost of tolls on the trip: 5.50 The total cost of the trip was 12.17
Email Me |
Office Hours |
My Home Page |
Department Home |
MCC Home Page
© Copyright Emmi Schatz 2002