MATLAB Answers

Why does rem(Centnum,5) give me an answer that is not zero?

1 view (last 30 days)
John Jamieson
John Jamieson on 27 Oct 2020
Answered: dpb on 27 Oct 2020
I created the following code in order to isolate canadian coins from the value of a cheque:
function [] = Jamiesonlab4 ()
Cheque=input('Enter the value of the cheque to be cashed: ');
Dollar=floor(Cheque);
Cent=Cheque-Dollar;
Centnum=Cent*100;
while (Cheque < 0) || (rem(Centnum,5) ~= 0)
Cheque=input('Input invalid, please enter a cheque value that cent value is divsible by five and non-negative: ');
Centnum=Cent*100;
end
Toonies=floor(Cheque/2);
Toonievalue=Toonies*2;
Remaining=(Cheque-Toonievalue);
Dollar=floor(Remaining);
Quarters=floor(Centnum/25);
Dimes=floor((Centnum-Quarters*25)/10);
Nickels=floor((Centnum-Quarters*25-Dimes*10)/5);
fprintf('The value in coins for this Cheque is:\n ')
if Toonies == 1
fprintf('There is %i toony\n', Toonies)
else
fprintf('There are %i toonies\n', Toonies)
end
if Dollar == 1
fprintf('There is %i Loony\n', Dollar)
else
fprintf('There are %i Loonies\n', Dollar)
end
if Quarters == 1
fprintf('There is %i Quarter\n', Quarters)
else
fprintf('There are %i Quarters\n', Quarters)
end
if Dimes == 1
fprintf('There is %i dime\n', Dimes)
else
fprintf('There are %i Dimes\n', Dimes)
end
if Nickels == 1
fprintf('There is %i nickel\n', Nickels)
else
fprintf('There are %i nickels\n', Nickels)
end
end
However, there is an error that occurs at the while loop. As if I enter an input such as 7.45, it claims it is invalid. Yet the number going into Centnum should be 45, which is divisible by 5. What is wrong here?

  0 Comments

Sign in to comment.

Answers (2)

Steven Lord
Steven Lord on 27 Oct 2020
>> x = 7.45;
>> d = floor(x);
>> c = x-d
c =
0.45
>> cn = 100*c;
>> cn - 45
ans =
1.4210854715202e-14
cn is not exactly forty-five one hundredths. No, this is not a bug. Just as you cannot represent, say, 1/3 as a decimal number exactly with a finite number of digits you also cannot represent 0.45 as a double precision number exactly.
You probably want to round cn before operating on it with the assumption that it contains an integer value.

  0 Comments

Sign in to comment.


dpb
dpb on 27 Oct 2020
>> format long,format compact
>> rem(Centnum,5)
ans =
1.421085471520200e-14
>>
0.05 cannot be stored exactly in floating point; hence rounding has bit you.
You'll need to round() your cent values to convert to exact integers.
<https://www.mathworks.com/matlabcentral/answers/57444-faq-why-is-0-3-0-2-0-1-not-equal-to-zero>

  0 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by