For loop not running properly

1 回表示 (過去 30 日間)
James Hill
James Hill 2019 年 5 月 10 日
コメント済み: Matt J 2019 年 5 月 10 日
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 日
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 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by