Checking for divisibility?

조회 수: 7 (최근 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