How to use while loop with an inequality condition
显示 更早的评论
Hi, I'm trying use a while loop in order to get a user to input a value in between a two separate values. (ie. 0.01 < x < 1000)
I currently have written this down in my script:
clear
clc
display('this is a test');
F = input('input test number: ');
while (F>1000 && F<0.01)
disp('test unsuccessful');
F = input('Please input new number: ');
end
display('Test successful');
Whenever I run the code, I input a number higher than 1000 or lower than 0.01 for 'x'. However, instead of moving into the while loop, it simply skips over and the prompt displays my 'Test successful' message.
I can get the code to work when only one condition is present but as soon as I include the second condition with the && statement, the while loop no longer operates.
What am I doing incorrectly?
edit: the purpose of me inputting a value above 1000 and below 0.01 is to trigger the while loop
_edit2:
instead of &&, || ended up working, using the same condtions: (F>1000 || F<0.01)
采纳的回答
更多回答(1 个)
Image Analyst
2013-11-25
Use OR instead of AND:
This works just fine:
F = input('input test number: ');
while (F>1000 || F<0.01)
disp('test unsuccessful');
F = input('Please input new number: ');
end
display('Test successful');
类别
在 帮助中心 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!