Given electricity unit charge, calculate the total electricity bill according to the given condition:
Units Range | Rate per Unit |
---|---|
For First 50 Units | Rs.0.50/unit |
For next 100 Units (51-150) | Rs.0.75/unit |
For next 100 Units (151-250) | Rs.1.20/unit |
For unit above 250 | Rs.1.50/unit |
Integer value indicating the number of units consumed
Print the output with floating point value indicating the total cost rounded off to two decimal places
-10^9 <= INPUT <= 10^9
#include <iostream> #include <iomanip> using namespace std; int main() { double units; cin >> units; // Handle invalid input if (units < 0) { cout << "0.00"; return 0; } double bill = 0.0; if (units <= 50) { bill = units * 0.50; } else if (units <= 150) { bill = (50 * 0.50) + (units - 50) * 0.75; } else if (units <= 250) { bill = (50 * 0.50) + (100 * 0.75) + (units - 150) * 1.20; } else { bill = (50 * 0.50) + (100 * 0.75) + (100 * 1.20) + (units - 250) * 1.50; } // Adding 20% surcharge bill += bill * 0.20; // Output rounded to 2 decimal places cout << fixed << setprecision(2) << bill; return 0; }
bill += bill * 0.20
fixed
and setprecision(2)
for 2 decimal placesThe key insight is that higher tiers include all previous tier costs:
Example: For 300 units, you don't pay 300 × 1.50. You pay:
int
instead of double
loses decimal precisionbill * 1.20
(which gives 120% total) instead of bill + bill * 0.20
Instead of adding surcharge separately:
// Original method: bill += bill * 0.20; // Alternative (multiply by 1.20): bill = bill * 1.20; // Or even simpler: bill *= 1.20;
All three methods give the same result. The last one is most concise!