Checking for divisibility?

12 次查看(过去 30 天)
arowan
arowan 2017-10-24
回答: Christoph F. 2017-10-25
I'm trying to check the validity of an input to make sure it is a positive multiple of 5. The input will most likely be in the format 0.00, representing a cash amount, to be outputted eventually as coins, excluding pennies. I've got the coin output down, but I can't figure out why the while validation is not working.
The code works for an input of 3.5, the first time I enter it, then I try 3.45 and get the 'invalid' response, then I try 3.5 again and get the 'invalid' response. Is this a result of rounding error?
cashChq = input('Enter the value of the cheque to be cashed: ');
nDollar = floor(cashChq);
centVal = cashChq - nDollar;
vC = centVal*100;
while (cashChq < 0) | (rem(vC,5) ~= 0)
cashChq = input('Invalid entry; pennies no longer exist! Please enter the value of the cheque to be cashed, \na non-negative dollar amount with cents in multiples of five: ');
end
nToon = floor(cashChq/2);
toonVal = nToon*2;
amtRem = (cashChq-toonVal);
nLoon = floor(amtRem);
nQrtrs = floor(vC/25);
nDms = floor((vC - nQrtrs*25)/10);
centRem = (vC - nQrtrs*25 - nDms*10);
nNckls = (centRem/5);
fprintf('There are %i toonies, %i loonies, %i quarters, %i dimes, and %i nickels.',nToon,nLoon,nQrtrs,nDms,nNckls);
end

回答(1 个)

Christoph F.
Christoph F. 2017-10-25
> Is this a result of rounding error?
No, it is the result of a bug. In your while loop, the code inputs a new value for cashChq, but it does not update vC, so the first value of vC is used over and over in the while conditional.

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by