The task
The starter code holds two values: the original price of a product in dollars and the discount as a percentage. The exercise is to print the price you pay after the discount. For a price of 150 and a discount of 10, the discount is 15 dollars and the final price is 135.
Two ways to see it
There are two equivalent routes to the same number.
- Subtract the discount. Compute the discount amount,
price * discount / 100, and take it off the price:price - price * discount / 100. - Keep the remaining share. A 15% discount means you still pay 100 - 15 = 85 percent of the price. So the final price is
price * (100 - discount) / 100.
The second route needs one multiplication and one division, and price appears only once in it. The lesson uses it.
Step by step
- Work out the percentage you keep:
100 - discount. With a discount of 15.0 this is 85.0. Wrap it in parentheses so the subtraction happens before the multiplication. - Multiply the price by that percentage: 70.0 * 85.0 is 5950.0.
- Divide by 100 to turn the percentage into a part of the price: 5950.0 / 100 is 59.5.
- Print the result with
println.
The solution in Scala
val price = 70.0
val discount = 15.0
println(price * (100 - discount) / 100)
The output is:
59.5
The subtracting version prints the same value for these numbers: price - price * discount / 100 also gives 59.5.
Details that matter in Scala
The values are written 70.0 and 15.0, with a decimal point, so Scala infers the type Double for both. Writing val price = 70 would infer Int instead. A Double calculation keeps decimals, and its output always includes a decimal part: with a price of 150.0 and a discount of 10.0, the same expression prints 135.0, not 135.
The parentheses are not optional. Compare:
println(price * (100 - discount) / 100)
println(price * 100 - discount / 100)
The second line subtracts only 0.15 from 7000.0 and prints 6999.85, which is not a discounted price. Multiplication and division run before subtraction, so a subtraction that must happen first needs parentheses.
If the values were Int, integer division would matter too. With a price of 70 and a discount of 15, price * (100 - discount) / 100 is 5950 / 100, which truncates to 59. The .5 is lost, so a price with cents needs Double.
Edge cases and common mistakes
- Printing the discount instead of the price. The amount taken off is 10.5 here. The price you pay is 59.5.
- Using the discount as a fraction.
price * discountmultiplies by 15, not by 0.15. The percentage must be divided by 100. - A discount of 0 or 100. A discount of 0 returns the full price, and a discount of 100 returns 0.0. The formula covers both.
- Hard-coded numbers. Use
priceanddiscount, so the answer follows the values.
Key takeaways
- The price after a discount is
price * (100 - discount) / 100. - Parentheses make the subtraction happen before the multiplication.
- Use
Doublefor prices, sinceIntdivision drops the fraction.
