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?

 Réponse acceptée

Matt J
Matt J le 10 Mai 2019
Modifié(e) : Matt J le 10 Mai 2019

0 votes

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 commentaires

James Hill
James Hill le 10 Mai 2019
Worked perfectly, thank you!
Matt J
Matt J le 10 Mai 2019
You're welcome, but since it worked, please Accept-click the answer.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Produits

Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by