How to use switch to choose and operator within a function?
3 ビュー (過去 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)
0 件のコメント
回答 (2 件)
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
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Multidimensional Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!