My while loop and rem function create an infinite loop

1 回表示 (過去 30 日間)
Krista Clark
Krista Clark 2021 年 2 月 27 日
コメント済み: Krista Clark 2021 年 2 月 28 日
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 日
You do give a chance for the user to enter x again, so you are testing the same x each time.
  3 件のコメント
Walter Roberson
Walter Roberson 2021 年 2 月 28 日
%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
Krista Clark
Krista Clark 2021 年 2 月 28 日
I had a typo in my code and ended up figuring it out. Thank you so much.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by