Using a letter as a case in a switch-case code
Afficher commentaires plus anciens
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
Réponses (1)
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 commentaire
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
Catégories
En savoir plus sur Conversion dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!