while loop or loop
Show older comments
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 Comment
Voss
on 10 Dec 2022
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?
Accepted Answer
More Answers (2)
Voss
on 10 Dec 2022
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 Comment
Image Analyst
on 10 Dec 2022
Moved: Voss
on 10 Dec 2022
Yes, the phrasing of the question is ambiguous.
Torsten
on 10 Dec 2022
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
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!