Back to Challenge Set 15

Code Challenge: Unit Price

Difficulty  

divider

The Brief

What they asked for
The shop compares products by price per unit so people can
see which is really cheaper. Bulk packs look cheap until
you do the division. I want to give it a price and a
count and get the per-unit figure back.

Write your requirements list before you write any code. Input, calculate, output, and anything you had to decide for yourself.


Notes

  • This one returns a value rather than printing it. That matters for the next note.
  • The last line compares the two packs. Decide it with an if that compares two calls to your method — something a method that only prints could never do.
  • Money shows two decimal places. Activity 1.9's :F2 does that, in the line that prints, not inside the method.
  • Think about the types. If the price were an int, the division would be Activity 1.6's integer division.

Where to Start

Only one-star challenges have this section. If you already know how to begin, skip it — and when you move up to two stars, working out the order yourself is part of the job.

  1. Work out both unit prices on paper first: 8.40 ÷ 12 and 19.50 ÷ 30.
  2. Write a method that takes a double price and an int count and returns the price per unit.
  3. Print both packs with two calls, formatted with :F2.
  4. Compare two calls in an if to print which pack is better.

Sample Output

Sample Output
Pack of 12 at $8.40 -> $0.70 each
Pack of 30 at $19.50 -> $0.65 each
The 30-pack is better.

Check the arithmetic by hand: 8.40 ÷ 12 and 19.50 ÷ 30 both come out to whole cents.


Submit

Your requirements list and your program file, named cc-unit-price.

Commence Challenge