How to let users enter integer, loop reenter again to them if they enter anything else

3 ビュー (過去 30 日間)
Daniel Chew
Daniel Chew 2022 年 3 月 26 日
コメント済み: Jan 2022 年 3 月 28 日
Hi, i want to prompt user to enter the integer only so that i can continue calculation part and i dont know how to do it.... i just only do it like this..
n = input('Enter number of patients : ');
while(n<2|n>100)
disp('You are only allowed within 2-100');
n = input('Please re-enter number of patients : ');
disp(' ');
end
but the things that i want is force user to enter integer if other than integer it will loop reenter stage, please help me...

回答 (1 件)

Jan
Jan 2022 年 3 月 26 日
ready = false;
while ~ready
n = input('Enter number of patients : ');
if ~isscalar(n) || n < 2 || n > 100 || abs(round(n)) ~= n
disp('You are only allowed within 2-100');
disp(' ');
else
ready = true;
end
end
  2 件のコメント
Daniel Chew
Daniel Chew 2022 年 3 月 27 日
編集済み: Daniel Chew 2022 年 3 月 27 日
Hi, if i dont want to put a range for the if situation
|| n < 2 || n > 100 ||
just only if not positive integer, it will loop till input is positive integer.
Can help me about how to write the code? Please?
Jan
Jan 2022 年 3 月 28 日
I'm not sure, if I understand you correctly. Do you mean:
if abs(round(n)) ~= n

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by