I have to use a while loop to ensure user input is an integer between 3 and 50. I set up constraints to do this but once I use the rem function to flag for noninteger it runs and infinite loop for my fprintf. What am I doing wrong?
%get user input
prompt = ('Enter a number for the length of your array: ');
x = input(prompt);
%have user input be an integer between 3-50
%test for noninteger
while (x < 3 || x > 50 || rem(x,1) ~= 0)
fprintf('Please enter an integer between 3 and 50: ');
end

 채택된 답변

Walter Roberson
Walter Roberson 2021년 2월 27일

0 개 추천

You do give a chance for the user to enter x again, so you are testing the same x each time.

댓글 수: 3

How would I go about giving the user an opportunity to put in a new x? I tried prompting them again in the while loop but it gives error.
%get user input
prompt = ('Enter a number for the length of your array: ');
x = input(prompt);
%have user input be an integer between 3-50
%test for noninteger
while (x < 3 || x > 50 || rem(x,1) ~= 0)
fprintf('Please enter an integer between 3 and 50: ');
x = input(prompt);
end
I had a typo in my code and ended up figuring it out. Thank you so much.

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

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2021년 2월 27일

댓글:

2021년 2월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by