Error with remainder (rem) and fix - change problem
Show older comments
Hi all, I'm working through the following problem:
=====================================
Design an algorithm (i.e., write the structure plan) for a machine that must give the
correct amount of change from a $100 bill for any purchase costing less than $100. The
plan must specify the number and type of all bills and coins in the change, and should
in all cases give as few bills and coins as possible. (If you are not familiar with dollars
and cents, use your own monetary system.)
=====================================
I have written a code that should do this, but occasionally have problems with the output. The problems are
(1) Sometimes, for example when the amount of change ends with .30, "Nickels" will be skipped and go to pennies. That is, instead of 1 quarter and 1 nickel, my output will say 1 quarter and 5 pennies.
EXAMPLE OUTPUT:
In what amount is the purchase? 90.70
Change given is: $9.3
Given in the form of 0 fifties, 0 twenties, 0 tens, 1 fives, 4 ones, 1 quarters, 0 dimes, 0 nickels, and 5 pennies.
(2) Sometimes, even when "Nickels" works (such as the case when the change ends in .40), the amount "Pennies" becomes something other than zero--in my case, 5.684341886080801e-13.
EXAMPLE OUTPUT:
In what amount is the purchase? 90.60
Change given is: $9.4
Given in the form of 0 fifties, 0 twenties, 0 tens, 1 fives, 4 ones, 1 quarters, 1 dimes, 1 nickels, and 5.6843e-013 pennies.
Here is my code. It overwrites "Remainder" throughout.
=====================================
Bill=100;
Purchase=input('In what amount is the purchase? ');
if Purchase==100
disp('No change given.')
else Purchase<Bill
Remainder=Bill-Purchase;
Fifties=fix(Remainder/50);
Remainder=rem(Remainder, 50);
Twenties=fix(Remainder/20);
Remainder=rem(Remainder, 20);
Tens=fix(Remainder/10);
Remainder=rem(Remainder, 10);
Fives=fix(Remainder/5);
Remainder=rem(Remainder, 5);
Ones=fix(Remainder/1);
Remainder=rem(Remainder, 1);
Quarters=fix(Remainder/0.25);
Remainder=rem(Remainder, 0.25);
Dimes=fix(Remainder/0.10);
Remainder=rem(Remainder, 0.10);
Nickels=fix(Remainder/0.05);
Remainder=rem(Remainder, 0.05);
Pennies=Remainder/0.01;
disp(['Change given is: $' num2str(Bill-Purchase)])
disp(['Given in the form of ' num2str(Fifties) ' fifties, ' num2str(Twenties) ' twenties, ' num2str(Tens) ' tens, ' num2str(Fives) ' fives, ' num2str(Ones) ' ones, ' num2str(Quarters) ' quarters, ' num2str(Dimes) ' dimes, ' num2str(Nickels) ' nickels, and ' num2str(Pennies) ' pennies.'])
end
Accepted Answer
More Answers (0)
Categories
Find more on Particle & Nuclear Physics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!