While loop with multiple conditional statements not working
3 次查看(过去 30 天)
显示 更早的评论
I created this while loop but when I input a fraction that should terminate the loop it doesn't exit the loop.
Ratio=1;
while (Ratio~=0 || Ratio~=(1/2) || Ratio~=1/3 || ...
Ratio~=1/5 || Ratio~=1/11 || Ratio~=5/7)
Ratio=(input('Enter a ratio (parts of milk)/(parts of coffee): '));
if (Ratio~=0 || Ratio~=1/2 || Ratio~=1/3 || ...
Ratio~=1/5 || Ratio~=1/11 || Ratio~=5/7)
disp('Invalid input');
end
end
2 个评论
采纳的回答
Image Analyst
2012-9-6
Just get rid of that problematic while/input way of doing it and do it like this:
button = menu('Enter the ratio (parts of milk)/(parts of coffee)', '0', '1/2', '1/3', '1/5', '1/11', '5/7')
switch button
case 1
ratio = 0;
case 2
ratio = 1/2;
case 3
ratio = 1/3;
case 4
ratio = 1/5;
case 5
ratio = 1/11;
case 6
ratio = 5/7;
end
fprintf('The user chose ratio = %f\n', ratio);
No while loop is needed because the user is not able to select a disallowed input.
更多回答(1 个)
Azzi Abdelmalek
2012-9-6
编辑:Azzi Abdelmalek
2012-9-6
you will never quit the loop because:
if a~=1 | a~= 2
this expression is always true
maby you should write
if a~=1 & a~= 2
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Programming Utilities 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!