Multiple switch cases for different operations

조회 수: 12 (최근 30일)
learningmat
learningmat 2014년 5월 1일
댓글: learningmat 2014년 5월 2일
Hi all, I want to do 3 processes. At first time i want to do some arithmetic operations which i can do it using switch cases.. After calculating i want to do another operation, for that i need to use first operation value. In third operation, again i have multiple case from that i have to choose what ever i want for that i want to use my second operation values...
If anyone know, pls suggest me too..
I tried this but i dint get the answer..
clear; clc; n=input('Please enter the figure:','s'); switch n case ('triangle'); n=3; sum=(n-1).*(180); case ('square'); n=4; sum=(n-1).*(180); case('pentagon'); n=5; sum=(n-2).*(180); case ('hexagon'); n=6; sum=(n-3).*(180); result=sum; end
result=input('Please enter the figure:','s'); switch result case('add'); addition=result+100; case('mul'); multn=result.*1; end
Anyother solutios (apart from switch case) also Welcome!
Thanks in advance.
  댓글 수: 1
dpb
dpb 2014년 5월 1일
편집: dpb 2014년 5월 1일
Please format your code to be legible...

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2014년 5월 1일
n=input('Please enter the figure:','s');
switch n
case ('triangle');
n=3;
sum=(n-1).*(180);
case ('square');
n=4;
sum=(n-1).*(180);
case('pentagon');
n=5;
sum=(n-2).*(180);
case ('hexagon');
n=6;
sum=(n-3).*(180);
result=sum;
end
result=input('Please enter the figure:','s');
switch result
case('add');
addition=result+100;
case('mul');
multn=result.*1;
end
You only saved result for the last case in the first switch block which is the variable you tried to use later. Put the statement
result=sum;
after the end of the block to make the assignment for each case. Or, better yet, since sum is not a descriptive variable name for those cases, anyway, replace
sum=...;
in each case by
result=...;
and dispense with the variable sum altogether. (Not to mention that by using sum as a variable you have aliased the builtin function sum which is used for + and much interesting behavior is sure to ensure. Don't do things like that!!! :) Of course, it's not necessarily easy to know as a Matlab newbie that there is a function sum since virtually always one use the '+' operator instead.
Then, your next problem is you duplicated the input text to ask for a figure again when instead you must have intended to ask for an arithmetic operation. So, you need to fix your prompt text. Then to compound the problem, you used the variable result that you just previously computed and want to use again as the target for that input thus overwriting it. Write something like
ops=input('Please enter the desired operation: (+,-)','s');
switch ops
...
Those should get you on your way...

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Power Converters에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by