Using a letter as a case in a switch-case code

조회 수: 6 (최근 30일)
Michael Foster
Michael Foster 2017년 2월 26일
편집: Adam 2017년 2월 28일
I'm trying to write a switch-case code that converts degrees and I ask for user input of F or C for determining which temperature to convert to. How do I get the code to accept F or C in the case? I know it has to do something with converting the letter to a string but I can't for the life of me find how to do it anywhere. This is my code right now:
temp = input('Input a temperature: ');
unit = input('Do you want to convert to Fahrenheit or Celsius (F/C): ');
switch unit
case F
temp=temp*1.8+32;
x=['The temperature is ',num2str(temp), ' degrees fahrenheit'];
disp(x)
case C
temp=(temp-32)*5/9;
y=['The temperature is ',num2str(temp), ' degrees celsius']
disp(y)
end

답변 (1개)

Stephen23
Stephen23 2017년 2월 26일
편집: Stephen23 2017년 2월 28일
Always use the 's' option with input, like this:
temp = str2double(input('Input a temperature: ','s'));
unit = input('Do you want to convert to Fahrenheit or Celsius (F/C): ','s');
switch unit
case 'F'
...
case 'C'
...
end
As the documentation states, the 's' options returns a string. You should always use the 's' option (even if you are getting a numeric value) because it is safer and more robust.
  댓글 수: 1
Adam
Adam 2017년 2월 28일
편집: Adam 2017년 2월 28일
Also note the other fundamental change in Stephen's code than the original that he didn't explicitly mention:
'F' and 'C' need to be strings in the switch statement, not just
case F
etc

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by