5 Functions [10 marks]
The cost of items purchased with cash in Canada are rounded to the nearest nickel. If a customer pays for a purchase with cash, then the price rounded to the nearest nickel must be computed before computing the amount of change due back to the customer. For example, suppose a customer pays 200 cents for a bill of 133 cents. The cash price of the bill is 135 cents, and the customer is due back 65 cents. To make change of 65 cents using the smallest number of coins, the cashier should return 2 quarters, 1 dime, and 1 nickel back to the customer.
Create and edit the function change.m
that computes the amount of change that should be returned to a customer who pays cash for a purchase:
function [c, q, d, n] = change(paid, price)
%CHANGE Amount of change for a cash purchase
% [c, q, d, n] = change(paid, price) returns the total amount of
% change c, the number of quarters q, the number of dimes d, and
% the number of nickels n for the given price and the amount
% of cash paid in cents. The price is rounded to the nearest
% nickel before computing the amount of change.
%
% The number of coins making up the total amount of change
% is the smallest number of coins possible.
end
The return value c
is the total amount of change due back to the customer; it should be equal to a multiple of 5
. The return values q
, d
, and n
are the number of quarters, dimes, and nickels, respectively, needed to make up the total amount of change c
. The total number of coins should be as small as possible; for example, if the total amount of change c
is 25 cents then your function should compute 1 quarter, 0 dimes, and 0 nickels instead of 0 quarters, 0 dimes, and 5 nickels.
You do not need to consider one-dollar and two-dollar coins in this question.
5.1 Hint
The trickiest part of this problem is computing the price rounded to the nearest nickel. To solve this part of the problem, consider what happens when you round the value price / 5
.
5.2 Example usage
% The example from the start of the question.
% Customer pays 200 cents for a bill of 133 cents.
% The 133 cents is rounded to the nearest nickel (135 cents).
% Then the amount of change is computed (65 cents).
% Finally the number of quarters, dimes, and nickels
% are computed.
[c, q, d, n] = change(200, 133);