For loop not running properly

I am still a beginner at MATLAB, and have written a simple function that pays a speficied bill using certain denominations.
Here's my code:
function [] = bill_payment ()
bill = input('Please enter the bill amount: ');
p = [50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01];
i = 1;
for j = 1:length(p)
while bill > 0
if p(i) <= bill
bill = bill - p(i);
disp(p(i))
else i = i+1;
end
end
end
The issue I have is that when I set bill to be a number ending in 0.09 (e.g. 17.99), I get the following output:
10
5
2
0.5000
0.2000
0.2000
0.0500
0.0200
0.0100
And the following error message:
Index exceeds the number of array elements (12).
Error in bill_payment (line 16)
if p(i) <= bill
What I don't understand is why my code moves onto the 0.01 option when p(11) = 0.02 and therefore p(11) = bill at that point in the code. Surely the output should be:
10
5
2
0.5000
0.2000
0.2000
0.0500
0.0200
0.0200
As that summed = 17.99 and the loop should stop when bill = 0?

 Accepted Answer

Matt J
Matt J on 10 May 2019
Edited: Matt J on 10 May 2019
17.99 does not have an exact binary floating point representation
>> format long
>> 17.99
ans =
17.989999999999998
So, you need to apply tolerances
function [] = bill_payment ()
bill = input('Please enter the bill amount: ');
p = [50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01];
i = 1;
for j = 1:length(p)
while bill+0.001 >= p(end) %<---- modify
if p(i) <= bill +.001 %<---- modify
bill = bill - p(i);
disp(p(i))
else i = i+1;
end
end
end

2 Comments

Worked perfectly, thank you!
You're welcome, but since it worked, please Accept-click the answer.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2018b

Asked:

on 10 May 2019

Commented:

on 10 May 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!