How to limit the user input to a specific range?

9 Ansichten (letzte 30 Tage)
Kundera
Kundera am 7 Jun. 2017
Kommentiert: Geoff Hayes am 7 Jun. 2017
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.

Akzeptierte Antwort

Geoff Hayes
Geoff Hayes am 7 Jun. 2017
Bearbeitet: Geoff Hayes am 7 Jun. 2017
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 Kommentare
Kundera
Kundera am 7 Jun. 2017
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 am 7 Jun. 2017
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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu External Language Interfaces finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by