フィルターのクリア

where can i use round function to make the function perfect

1 回表示 (過去 30 日間)
yared Zeleke
yared Zeleke 2018 年 3 月 15 日
編集済み: Roger Stafford 2018 年 3 月 15 日
function [amt_ret, x]= calculate_change(tendered,price)
%--------------------------------------------------------------------------------------------------------%
% A. peter 2-24-2018 %
% This function calculates the change from a purchase given the %
% amount tendered and the purchase price. The function also provides %
% minimum denominations to make up the change. %
% %
% Calling syntax: %
% [amt_ret, xprice] = calculate_change(tendered,price) %
% %
% inputs: tendered = amount of currency given to the cashier [$] %
% price = purcahse price [$] %
% %
% output: change = tendered - price [$] %
% x = vector indicating the amountof each %
% denomination to make up the change %
% %
%---------------------------------------------------------------------------------------------------------%
%
format bank
denoms=[50,20,10,5,1,0.25,0.10,0.05,0.01]; % denominations vector
change=tendered-price;
for k=1:length(denoms)
index=0;
while change+75*eps>=denoms(k)
index=index+1;
change=change-denoms(k);
end
x(k)=index;
end
amt_ret=sum(denoms.*x);
error = change - amt_ret;
end

採用された回答

Roger Stafford
Roger Stafford 2018 年 3 月 15 日
編集済み: Roger Stafford 2018 年 3 月 15 日
I would suggest initially multiplying both 'tendered' and 'price' by 100 and using 'round' on the result:
tendered = round(100*tendered);
price = round(100*price);
so as to represent pennies instead of dollars. Similarly your 'denoms' should each be 100 times as great. After that you will be working strictly with integers and have no need for such stuff as "while change+75*eps>=denoms(k)". In fact you can use the 'mod' function to accomplish in one step a whole 'while' loop computation. Of course at the last step you need to divide 'amt_ret' by 100 to get back to dollars.
  1 件のコメント
Roger Stafford
Roger Stafford 2018 年 3 月 15 日
編集済み: Roger Stafford 2018 年 3 月 15 日
Instead of 'mod' it is easier to use 'floor' and division by 'denoms'. Since only integers are involved there should be no errors.
change = tendered-price;
denoms = [5000,2000,1000,500,100,25,10,5,1];
m = length(denoms);
x = zeros(1,m);
for k = 1:m
x(k) = floor(change/denoms(k));
change = change-x(k)*denoms(k);
end
amt_ret = sum(denoms.*x)/100;

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeBloomberg EMSX についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by