I have created a function in MATLAB, that displays the amount of change due (GB Currency) when the cost of an item and the amount of money given for the item are input.
function C = myChange(cost, paid)
M = [50, 20, 10, 5, 2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01];
C = [];
for i = 1:size(M,2)
if (paid - cost) >= M(i)
C = [M(i); myChange(cost, paid-M(i))];
break
elseif (paid - cost) == 0
break
end
end
end
The function seems to work perfectly when integers are used,
>> myChange(2, 4)
ans =
2
>> myChange(20, 32)
ans =
10
2
However, sometimes, but not all the time, when decimal points are incorporated in the inputs, the amount of change comes up one penny (cent) short
>> myChange(2, 3.25)
ans =
1.0000
0.2000
0.0200
0.0200
In this case, though, the correct change is once again displayed
>> myChange(27.57, 100)
ans =
50.0000
20.0000
2.0000
0.2000
0.2000
0.0200
0.0100
I'm not sure what could be causing this inconsistency, having played around with the function for while now to no avail. Any help is much appreciated, thanks.