Calculate Price with Discount in C++
In this exercise, you will create a program that calculates the final price of a purchase after applying a dynamic discount. The program prompts the user for the original amount and uses conditional logic to determine the applicable savings rate.
This is a fundamental exercise to practice arithmetic operations, formatting floating-point numbers, and nested if-else structures.
Discount Logic Breakdown
20% Discount
Applied when the total is ≥ $100. Ideal for wholesale or large orders.
10% Discount
Applied for totals between $50 and $99.99.
5% Discount
Applied for any purchase below $50 as a baseline reward.
Precision Matters: setprecision(2)
When dealing with money, we use the <iomanip> library. The command fixed << setprecision(2) ensures that the program always displays exactly two digits after the decimal point (e.g., $96.00 instead of $96).
Objectives
- 1. Input the original purchase amount using
doublefor precision. - 2. Implement conditional branches to select the correct discount percentage.
- 3. Calculate the discount value and subtract it from the total.
- 4. Output formatted results showing the original price, the percentage applied, and the final cost.
Example C++ Code
#include <iostream>
#include <iomanip> // For output formatting
using namespace std;
int main() {
double totalAmount, finalPrice, discount;
cout << "Enter the total amount of your purchase: $";
cin >> totalAmount;
// Logic for discount tiers
if (totalAmount >= 100) {
discount = 0.20; // 20%
} else if (totalAmount >= 50) {
discount = 0.10; // 10%
} else {
discount = 0.05; // 5%
}
finalPrice = totalAmount - (totalAmount * discount);
// Formatted Output
cout << fixed << setprecision(2);
cout << "Original amount: $" << totalAmount << endl;
cout << "Discount applied: " << (discount * 100) << "%" << endl;
cout << "Final price after discount: $" << finalPrice << endl;
return 0;
}
Console Output:
Original amount: $120.00
Discount applied: 20%
Final price after discount: $96.00