Using a letter as a case in a switch-case code
9 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
Stephen23
2017-2-26
编辑:Stephen23
2017-2-28
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.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!