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?

 채택된 답변

Matt J
Matt J 2019년 5월 10일
편집: Matt J 2019년 5월 10일

0 개 추천

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

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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

제품

릴리스

R2018b

질문:

2019년 5월 10일

댓글:

2019년 5월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by