Switch Statements for detecting the sign of a number
23 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
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 个评论
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
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!