필터 지우기
필터 지우기

How to combine two different conditions for a user?

조회 수: 1 (최근 30일)
Sara Williams
Sara Williams 2018년 2월 9일
댓글: Sara Williams 2018년 2월 10일
I want the user to input a number that is both an integer and within the range of 1-59. I have managed to do these two things separately, creating two different variables, but I want to combine them to just create one variable.
This is how I wrote them out separately:
while true
prompt2 = 'choose your 2nd number';
x2 = input('choose your 2nd number: ', 's');
if all(isstrprop(x2, 'digit'))
x2 = str2double(x2);
break;
else
disp('Must be an integer');
end
end
while true
prompt2 = 'choose your 2nd number';
x2 = str2double(input('choose your 2nd number: ', 's'));
if (x2 >= 1 && x2 <= 59)
break;
else
disp('Must be between 1 and 59');
end
end
But how would you combine them into 1 so that if you selected a non integer, or one outside the range an error would occur?

답변 (1개)

Greg
Greg 2018년 2월 9일
편집: Greg 2018년 2월 9일
Personally, I would just round the input (and inform the user if you choose). Then, all you need is check the range.
x2 = NaN;
while isnan(x2) || x2 < 1 || x2 > 59
prompt2 = 'choose your 2nd number: ';
x2 = round(str2double(input(prompt2, 's')));
end
  댓글 수: 2
Greg
Greg 2018년 2월 9일
Additionally, your prompt should completely describe the conditions of the input. 'Choose an integer: 1 <= x <= 59'
Sara Williams
Sara Williams 2018년 2월 10일
Thank you for your help!

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

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by