changine if-elseif to a switch-case structure
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Mike
am 30 Okt. 2013
Bearbeitet: John Kelly
am 10 Nov. 2017
rewrite the following code segment containing an if-elseif using a switch-case structure instead of the if-elseif. The code should not contain any ifs and should employ minimum number of disp commands. assume a is always a positive number
if a<60
disp('f)
elseif a<70
disp('d')
else
disp('good job')
my attempt was a=input(' ') switch a case a<60 disp('f') case a>= 60 & a<70 disp('d') otherwise disp('edit you') end
2 Kommentare
dpb
am 30 Okt. 2013
Homework needs an honest attempt first -- post your work and a specific question...meanwhile, there's always
doc switch
with and example to get you kick-started...
Akzeptierte Antwort
sixwwwwww
am 31 Okt. 2013
Dear Mike, You can convert if-else code to switch case structure as follows:
InputValue = input('Input value: ');
val = sum(InputValue < [70 60]);
switch val
case 2
disp('f')
case 1
disp('d')
otherwise
disp('Good job')
end
I hope it helps. Good luck!
3 Kommentare
Sabri Çetin
am 22 Jun. 2016
Can you generalize your answer for arbitrary conditions?
There is an obvious generalization by using several switch statements, but you did this with only one switch statement, but your answer somehow depends on the condition.
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!