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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by