📅  最后修改于: 2021-01-07 02:13:38             🧑  作者: Mango
开关是另一种条件语句,它执行多个语句组中的一个。
switch switch_expression
case case_expression1
Statements
case case_expression2
Statements
case case_expressionN
Statements
otherwise
Statements
End
类似于if块, switch块将测试每种情况,直到case_expression中的一个为true为止。评估为:
% program to check whether the entered number is a weekday or not
a = input('enter a number : ')
switch a
case 1
disp('Monday')
case 2
disp('Tuesday')
case 3
disp('Wednesday')
case 4
disp('Thursday')
case 5
disp('Friday')
case 6
disp('Saturday')
case 7
disp('Sunday')
otherwise
disp('not a weekday')
end
输出:
enter a number: 4
Thursday
% Program to find the weekday of a given date
% take date input from keyboard in the specified format
d = input('enter a date in the format- dd-mmm-yyyy:',"s")
% weekday function takes input argument
% and returns the day number & day name of the particular date.
[dayNumber, dayName] = weekday(d,'long',"local");
% use switch and case to display the output as per the entered input
switch dayNumber
case 2
x = sprintf('Start of the week-%s-:%d',dayName,dayNumber);
disp(x)
case 3
x = sprintf('%s:%d',dayName,dayNumber);
disp(x)
case 4
x = sprintf('%s:%d',dayName,dayNumber);
disp(x)
case 5
x = sprintf('%s:%d',dayName,dayNumber);
disp(x)
case 6
x = sprintf('Last working day-%s-of the week:%d',dayName,dayNumber);
disp(x)
otherwise
disp('weekend')
end