How to limit the user input to a specific range?

조회 수: 9 (최근 30일)
Kundera
Kundera 2017년 6월 7일
댓글: Geoff Hayes 2017년 6월 7일
Hi, I want to print in the command prompt "Enter the length in meters" adding a limitation that the input must be between o to 10. If something falls outside the range, the sentence "Not a valid number. Please try again" will be displayed. I tried with the following but Matlab disregard the condition. How should I define it instead?
while 1
len = str2double(input('Enter the length in meters: ','s'));
if len
break;
end
disp('Not a valid number. Please try again')
end
Thanks for your time.

채택된 답변

Geoff Hayes
Geoff Hayes 2017년 6월 7일
편집: Geoff Hayes 2017년 6월 7일
Valentina - your condition is
if len
This will always be true if len is not zero. If you wish to restrict your length to the interval 0 and 10, then your condition would be
if len >= 0 && len <= 10
break;
end
  댓글 수: 2
Kundera
Kundera 2017년 6월 7일
Thank you. It works perfectly, but still I don't understand one thing. I want the range to include the ending 0 and 10. Using your code it works, but I don't see why of using the output 0. To me, if the input is 0, the condition len >= 0 should break and send me the 'Not a valid number. Please try again'. But it is not the case.
Geoff Hayes
Geoff Hayes 2017년 6월 7일
But isn't 0 a valid length? From your original comment, that the input must be between o to 10. If 0 is invalid, then change your condition to
if len > 0 && len <= 10
break;
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 External Language Interfaces에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by