How to use switch to choose and operator within a function?

1 次查看(过去 30 天)
Having issues relying on switch to decide an operator within a function. I know using if, else statements would be easier but using switch is part of the assignment. How can I fix this function in order to make it work properly?
---function---
function r=calc_switch(a,b)
op=input('Input Operator: ');
switch(op)
case(op=='+')
r=a+b;
case(op=='-')
r=a-b;
case(op=='*')
r=a*b;
case(op=='/')
r=a/b;
end
fprintf('The value r is: %d\n',r)
---command window---
>> calc_switch(5,5)
Input Operator: '/'
Undefined function or variable 'r'.
Error in calc_switch (line 13)
fprintf('The value r is: %d\n',r)

回答(2 个)

Adam
Adam 2017-4-10
编辑:Adam 2017-4-10
case(op=='+')
is not valid. Use
case('+')
instead

Guillaume
Guillaume 2017-4-10
As Adam said, your case syntax is not valid.
The reason you got the error Undefined function or variable 'r'. is because none of your case applied, therefore r never got created.
As it's very easy for the user to enter a wrong input, you really ought to respond to that case rather than let your script error with an obscure message. So this should tell you to add an otherwise option to your switch:
switch op
case ...
...
case ...
...
otherwise
error('Could not recognise operator: %s', op);
end
Note, however, that the whole thing could be written without switch, using look-up tables instead:
function r=calc_switch(a, b)
operators = '+-*/';
opfuns = {@plus, @minus, @mtimes, @mrdivide}; %actual function to invoke, in the same order as operators . Note that you may prefer @times and @rdivide to perform memberwise multiplication and division
op = input('Input Operator: ');
[valid, opidx] = ismember(op, operators);
if ~valid
error('Could not recognise operator: %s', op);
end
r = opfun{opidx}(a, b);
end

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by