i want the user the to give an estimation, how would i use a while or for loop so if the value is 2500<x<2501, it repeats the question until the user is correct. Thanks very much

1 件のコメント

Voss
Voss 2022 年 12 月 10 日
Your question seems to imply that x <= 2500 or x >= 2501 is the "correct" answer in this context. Is that right?
Or is 2500<x<2501 the "correct" answer, and you want the loop to run as long as x <= 2500 or x >= 2501?

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

 採用された回答

Image Analyst
Image Analyst 2022 年 12 月 10 日

0 投票

See this snippet and adapt as needed:
% Demonstration of how to avoid an infinite loop by setting up a failsafe.
% Set up a failsafe
maxIterations = 10; % Way more than you think it would ever need.
loopCounter = 0;
% Now loop until we obtain the required condition: x is between 2500 and 2501.
% If that never happens, the failsafe will kick us out of the loop so we do not get an infinite loop.
x = 0; % Initialize so we can enter the loop the first time.
while ((x < 2500) || (x > 2501)) && loopCounter < maxIterations
x = input('Enter x (or Ctrl c to quit) : ');
loopCounter = loopCounter + 1;
fprintf('On Iteration #%d, x = %f.\n', loopCounter, x)
end
% Alert user if we exited normally, or if the failsafe kicked us out to avoid an infinite loop.
if loopCounter < maxIterations
% Then the loop found the condition and exited early, which means normally.
fprintf('Loop exited normally after %d iterations.\n', loopCounter);
else
% Then the loop never found the condition and exited when the number of iterations
% hit the maximum number of iterations allowed, which means abnormally.
fprintf('Loop exited abnormally after iterating the maximimum number of iterations (%d) without obtaining the exit criteria.\n', maxIterations);
end
fprintf('All done after %d iterations.\n', loopCounter)
To learn other fundamental concepts, invest 2 hours of your time here:

その他の回答 (2 件)

Voss
Voss 2022 年 12 月 10 日

0 投票

Something like this:
x = 2500.5; % initialize x to a value that will cause the loop to run
while x > 2500 && x < 2501
% code to "repeat the question" and get a new x value goes here
end
Or this:
while true
% ask the question and get an x value here
if x <= 2500 || x >= 2501
% x outside the range: exit the loop
break
end
end

1 件のコメント

Image Analyst
Image Analyst 2022 年 12 月 10 日
移動済み: Voss 2022 年 12 月 10 日
Yes, the phrasing of the question is ambiguous.

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

Torsten
Torsten 2022 年 12 月 10 日

0 投票

prompt = "Input x ";
x = input(prompt)
while x > 2500 && x < 2501
disp("Wrong value for x")
disp("x must not be in the interval (2500 2501)"
prompt = "Input x ";
x = input(prompt)
end

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

質問済み:

2022 年 12 月 10 日

移動済み:

2022 年 12 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by