fork download
  1. // Miles per Gallon Program
  2. // This program calculates how many miles a car can drive per gallon of gas.
  3.  
  4. #include <iostream>
  5. #include <iomanip>
  6. using namespace std;
  7.  
  8. int main() {
  9. double gallons, miles, mpg;
  10.  
  11. // Ask user for input
  12. cout << "Enter the number of gallons the car can hold: ";
  13. cin >> gallons;
  14.  
  15. cout << "Enter the number of miles the car can be driven on a full tank: ";
  16. cin >> miles;
  17.  
  18. // Prevent division by zero
  19. if (gallons <= 0) {
  20. cout << "Error: Gallons must be greater than zero." << endl;
  21. return 1;
  22. }
  23.  
  24. // Calculate MPG
  25. mpg = miles / gallons;
  26.  
  27. // Display result
  28. cout << fixed << setprecision(2);
  29. cout << "\nThe car's gas mileage is " << mpg << " miles per gallon." << endl;
  30.  
  31. return 0;
  32. }
  33.  
Success #stdin #stdout 0.01s 5272KB
stdin
Standard input is empty
stdout
Enter the number of gallons the car can hold: Enter the number of miles the car can be driven on a full tank: 
The car's gas mileage is 1.49 miles per gallon.