Add a discount and sales tax to a single-item purchase using integer math.
You start with: an empty editor (no starter code). Declare this data yourself:
let item = "Coffee Mug";
let price = 12;
let quantity = 3;
let tax_rate = 8;
let discount = 5;
Build:
Subtotal: $36 Discount: $5 Tax: $2 Total: $33
Rules:
subtotal = price * quantity.after_discount = subtotal - discount(the discount is a flat amount taken off before tax).tax = after_discount * tax_rate / 100(integer division, so the result is rounded down). The tax is charged on the discounted amount.total = after_discount + tax.- Build four lines (
Subtotal,Discount,Tax,Total) and join them with a newline"\n"into one stringresult, then print it withprintln!("{}", result).
Compute the four numbers (
subtotal, after_discount, tax, total) before formatting.
Use
format!("Total: ${}", total) to build each line from a number.
Rust's
i32 / i32 truncates, so after_discount * tax_rate / 100 already rounds down.
let item = "Coffee Mug";
let price = 12;
let quantity = 3;
let tax_rate = 8;
let discount = 5;
let subtotal = price * quantity;
let after_discount = subtotal - discount;
let tax = after_discount * tax_rate / 100;
let total = after_discount + tax;
let line1 = format!("Subtotal: ${}", subtotal);
let line2 = format!("Discount: ${}", discount);
let line3 = format!("Tax: ${}", tax);
let line4 = format!("Total: ${}", total);
let result = format!("{}\n{}\n{}\n{}", line1, line2, line3, line4);
println!("{}", result);
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
