does anyone know how to rewrite this into switch/case statements

2 次查看(过去 30 天)
n=input('Please enter a positive or negative integer: ');
if n < -2 || n > 5
disp(n/2)
else
if n <= 3
if n >= 0
disp(floor(n/2))
else
disp(ceil(n))
end
else
disp(1)
end
end
  6 个评论
John D'Errico
John D'Errico 2018-10-30
Yeah, I figured it was HW. Stupid stuff. Teacher makes you do silly things for no good reason. Grump. Rant. Grumble. ;-)
So, are you asking how to do different things, based on which range n falls in, using a switch/case?
Pablo Garcia
Pablo Garcia 2018-10-30
The homework is basically just asking us to switch the above code from an if/if-else statement to a switch/case statement that still keeps the same purpose. I understand how to use switch/case statements but I'm having trouble with the inequalities

请先登录,再进行评论。

采纳的回答

John D'Errico
John D'Errico 2018-10-30
The immediate answer is to look at histcounts. It will allow you to set up a series of break points, returning an integer that indicates which regime a number falls into. So it looks like the various cases you might care about are:
breaks = [-2 0 3 5]
Then the third output from histcounts will be an integer, depending on which interval a point falls in. The problem is, you have a special issue, in that histcounts tests to see if a point is in an interval if it is >= the breaks.
So histc would put 3 and 4 into the same bin! And it looks like you wants histcounts to do something different for n==3 versus n==4.
If you know that n is always an integer, that means you wanted to set the break points as
breaks = [-2 0 4 5];
Anyway, histcounts may be beyond the scope of this problem, since it has a simple resolution.
switch n
case {-1 -2}
% do whatever you might do when n==-1 or -2
case {0 1 2 3}
% do whatever you might do when n lives in this range
case {4 5}
% do whatever you might do when n lives in this range
otherwise
% we covered all the other cases, so this is what happens when n < -2 or > 5
disp(n/2)
end
  3 个评论
John D'Errico
John D'Errico 2018-10-30
编辑:John D'Errico 2018-10-30
That is exactly what otherwise does. It covers all cases that were not explicitly mentioned in the cases. The problem would be if you wanted to do something different for n<-2 compared to n>5. Then you would need to get trickier. For example, you might need to put an if inside the otherwise block.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by