Using a letter as a case in a switch-case code
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposte (1)
Stephen23
il 26 Feb 2017
Modificato: Stephen23
il 28 Feb 2017
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.
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!