switch case and inequalities

18 ビュー (過去 30 日間)
Rachel Dawn
Rachel Dawn 2018 年 2 月 7 日
回答済み: Stephen23 2018 年 2 月 8 日
So, say I wanted to disp('that's impossible') if a user enters an age over 150 or less than 0?
How could I do this for a switch case if I can't use inequalities?
I know that between 0 and 150, I could use case num2cell(0:150), but if I don't have bounds for less than zero & over 150, how could I use num2cell?

回答 (2 件)

Stephen23
Stephen23 2018 年 2 月 8 日
It is possible with switch:
age = 200;
switch true
case age>150
disp('that''s impossible!')
case age<0
disp('not born yet!')
end
But using if and elseif might be clearer.

Aaron Winch
Aaron Winch 2018 年 2 月 7 日
switch Age
case num2cell(0:150)
disp('Valid')
otherwise
disp('that''s impossible')
end
  2 件のコメント
Rachel Dawn
Rachel Dawn 2018 年 2 月 8 日
hmm.. but what if I wanted to display "that's impossible" for age <0 and "that's not likely" for age >150? Is "switch" code for this possible?
PS thank you!
Aaron Winch
Aaron Winch 2018 年 2 月 8 日
switch Age
case num2cell(0:150)
disp('Valid')
otherwise
if(Age<0)
disp('that''s impossible')
else
disp('that''s unlikely')
end
end
Is there a reason you want to use a switch? If Age is manual input by a user, I think "case num2cell(0:150)' will only match with integers between 0 and 150, so if a user has the ability to input 25.75 for Age, nothing will happen with this logic.

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by