Switch Statements for detecting the sign of a number

12 ビュー (過去 30 日間)
Std1
Std1 2020 年 4 月 14 日
コメント済み: DGM 2024 年 10 月 1 日
Hi, I want to detect the sign of a number that I entered with using switch statements
I wote the code there is a problem about returning the results
When I entered -1, the matlab returns: I do not know
Also When I entered 0, the matlab returns: The number is negative
Help me about this problem. This case could be easily done with using for loop but I want this with switch statements.
n=input('Enter a number ');
switch n
case n<0
disp('The number is negative')
case n==0
disp('The number is 0')
case n>0
disp('The number is positive')
otherwise
disp('I do not know')
end

回答 (2 件)

Walter Roberson
Walter Roberson 2020 年 4 月 14 日
switch n case n<0 is effectively
if any(ismember(n, n<0))
n<0 is going to evaluate to either 0 or 1, and that is going to be compared to the number itself. Neither 0 nor 1 are less than 0, so n<0 will always be false (0), and ismember(0,0) is true so you would get a match.
If you must use logical tests in the case (not recommended because that is confusing to most people) then you need to use
switch true
  2 件のコメント
Std1
Std1 2020 年 4 月 14 日
Thank you very much, I am just learning Matlab and I want to try every functions on a problem. That is why I am using Switch statement.
DGM
DGM 2024 年 10 月 1 日
Alternatively
switch sign(n)
case -1
disp('The number is negative')
case 0
disp('The number is 0')
case 1
disp('The number is positive')
otherwise
% this will occur for NaN
disp('n is not a number')
end

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


Mitish
Mitish 2024 年 10 月 1 日
n=input('enter the number')
switch true
case n<0
disp('negative number')
case n>0
disp('positive number')
case n==0
disp('zero')
otherwise
disp('other value')
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by