Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //NickG
- //Gas Calculator
- #include <iostream>
- #include <iomanip>
- using namespace std;
- void validate (float* data) {
- while(cin.fail()) { //Input validation loop
- cin.clear(); //Clear flags
- cin.ignore(); //Clear input buffer
- cout<<"Invalid Input - Please input a number:";
- cin>>(*data);
- }
- }
- int main () {
- float gallons, miles, price, totalg, totalp, totalm, totalt;
- char response;
- cout << fixed << setprecision (2); //Set the output precision and output format
- do { //Primary loop start
- do {
- if (gallons!=0)
- {cout << "Enter the gallons used:";}
- else //If gallons is 0, ask for a non-zero number
- {cout << "Enter a non-zero number:";}
- cin >> gallons;
- validate (&gallons);
- } while (gallons==0);
- cout << "Enter the miles driven:";
- cin >> miles;
- validate (&miles);
- cout << "Enter the price/gallon of gas:$";
- cin >> price;
- validate (&price);
- totalg+=gallons; //increment total gallons
- totalp+=(price*gallons); //increment total price
- totalm+=miles; //increment total miles
- totalt++; //increment total trips
- cout <<endl << "The mpg for this trip was " << miles/gallons << endl;
- cout << "The cost of this trip was $" << price*gallons << endl;
- do { //Response loop
- cout << "Would you like to calculate another trip? (y/n)";
- cin >> response;
- } while ((response!='y')&&(response!='Y')&&(response!='n')&&(response!='N')); //Wait for valid input
- cout << endl;
- } while ((response=='y')||(response=='Y')); //Primary loop end
- cout << "Total miles traveled: " << totalm <<endl; //Print averages
- cout << "Total price of trips: $" << totalp <<endl;
- cout << "Total gallons of gas used: " << totalg <<endl;
- cout << "The average miles driven was: " << totalm/totalt <<endl;
- cout << "The average mpg was: " << totalm/totalg <<endl;
- cout << "The average price of a trip was: $" << totalp/totalt <<endl;
- #if defined (__WIN32__) || defined (__WIN32)
- cout << "Press any key to continue...";
- cin.ignore(255,'/n');
- cin.get();
- #endif
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement