In: Computer Science
Suppose a gas company bases its charges on consumption according to the following table:
Gas Used | Rate |
---|---|
First 70 cubic meters | $5.00 minimum cost |
Next 100 cubic meters | $0.05 per cubic meter |
Next 230 cubic meters | $0.025 per cubic meter |
Above 400 cubic meters | $0.015 per cubic meter |
Write a program in C++ that asks the user to enter the number of
cubic meters of gas used, calculates the charges, and displays the
total charge.
// C++ program that asks the user to enter the number of cubic meters of gas used, calculates the charges, and displays the total charge.
#include <iostream>
using namespace std;
int main()
{
double gasUsed, charges;
// input the number of cubic meters of gas used
cout<<"Enter the number of cubic meters of gas used: ";
cin>>gasUsed;
charges = 5; // set charges to base charge of 5
gasUsed -= 70; // subtract first 70 cubic meters from gasUsed
// initial gasUsed > 70
if(gasUsed > 0){
// next 100 cubic meters is charged at $0.05 per cubic meter
if(gasUsed > 100) // gasUsed > 100
charges += 100*0.05; // add charges for next 100
else // add charges for the left gas
charges += (gasUsed)*0.05;
gasUsed -= 100; // subtract 100 from gas used
}
// initial gasUsed > 170
if(gasUsed > 0)
{
// next 230 cubic meters is charged at $0.025 per cubic meter
if(gasUsed > 230) // gasUsed > 230
charges += 230*0.025; // add charges for next 230
else // add charges fro left gas
charges += gasUsed*0.025;
gasUsed -= 230; // subtract 230 from gas used
}
// initial gasUsed > 400
if(gasUsed > 0)
{
// above 400 cubic meters is charged at $0.015 per cubic
meter
charges += gasUsed*0.015; // add charges for left gas
}
// display the charges to 2 decimal places
cout<<fixed;
cout.precision(2);
cout<<"Total charge: $"<<charges<<endl;
return 0;
}
//end of program
Output: