필터 지우기
필터 지우기

Help with using a switch statement

조회 수: 2 (최근 30일)
Marina Christakos
Marina Christakos 2019년 1월 23일
편집: Stephen23 2019년 1월 23일
I was supposed to write a code that asks for a letter and a number. If the variables 'c', 't', or 's' were entered, it should find the cosine, tangent, or sine of the entered number. (also had to use a switch statement). When I run my code it asks for the number and letter but doesn't compute anything. How would I change my code to actually compute the value of the entered number?
q = input('enter number');
letter = input('enter letter');
't' == 'tangent';
'c' == 'cosine';
's' == 'sine';
switch letter
case {'s'}
letter = 's';
disp(sine(q));
case {'c'}
letter = 'c';
disp(cosine(q));
case {'t'}
letter = 't';
disp(tangent(q));
otherwise
letter = 'unknown';
end

채택된 답변

Stephen23
Stephen23 2019년 1월 23일
편집: Stephen23 2019년 1월 23일
val = str2double(input('enter number','s'));
chr = input('enter letter','s');
switch chr
case 's'
disp(sin(val))
case 'c'
disp(cos(val))
case 't'
disp(tan(val))
otherwise
error('oh no!')
end
A simple internet search would have quickly shown you the correct functions for calculating the sine, cosine, and tangent. Reading the documentation is much more reliable than guessing.
Note that all of your lines with == do nothing: e.g. the line
't' == 'tangent';
performs an element-wise comparison of the characters in the character vector 'tangent' with the single character 't'. Without even running that code I can tell you that the output will be:
[1,0,0,0,0,0,1]
because only the first and last characters are t's. In any case, you do not allocate this logical vector to anything, or use it in any way, so it is simply discarded. Ditto all the other == lines.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by