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

3 ビュー (過去 30 日間)
Alexander Nicholas
Alexander Nicholas 2017 年 4 月 10 日
回答済み: Guillaume 2017 年 4 月 10 日
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
  3 件のコメント
Thorsten
Thorsten 2017 年 4 月 10 日
BTW: You don't need the parentheses around '+'.
Stephen23
Stephen23 2017 年 4 月 10 日

サインインしてコメントする。


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 Center および File ExchangeMultidimensional Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by