Temperature conversion what does this code lack?

1 次查看(过去 30 天)
I am working on a code that converts temperature C, F and K. So l came up with this code:
function T = convertTemperature(T, unitFrom, unitTo)
Celsius = 'Celsius';
Fahrenheit = 'Fahrenheit';
Kelvin = 'Kelvin';
if strcmp(Celsius, Fahrenheit)
T = (1.8 * T) + 32;
elseif strcmp(Celsius, Kelvin)
T = T + 273.15;
elseif strcmp(Fahrenheit, Celsius)
T = (T-32)/1.8;
elseif strcmp(Fahrenheit, Kelvin)
T = (T + 459.67)/1.8;
elseif strcmp(Kelvin, Celsius)
T = T - 273.15;
elseif strcmp(Kelvin, Fahrenheit)
T = 1.8 * T - 459.67;
end
It seems that it is missing something, because when i use the testcode:
convertTemperature(50, 'Fahrenheit', 'Celsius')
l get the output: ans = 50
but I know from the equations that it should give 10.

回答(1 个)

Star Strider
Star Strider 2016-8-7
You need to be comparing your ‘unitFrom’ and ‘unitTo’ in your if blocks. I did the first one:
function T = convertTemperature(T, unitFrom, unitTo)
Celsius = 'Celsius';
Fahrenheit = 'Fahrenheit';
Kelvin = 'Kelvin';
if strcmp(unitFrom, Celsius) & strcmp(unitTo, Fahrenheit)
T = (1.8 * T) + 32;
elseif strcmp(Celsius, Kelvin)
T = T + 273.15;
elseif strcmp(Fahrenheit, Celsius)
T = (T-32)/1.8;
elseif strcmp(Fahrenheit, Kelvin)
T = (T + 459.67)/1.8;
elseif strcmp(Kelvin, Celsius)
T = T - 273.15;
elseif strcmp(Kelvin, Fahrenheit)
T = 1.8 * T - 459.67;
end
end
and when I ran this line:
Test = convertTemperature(10, 'Celsius', 'Fahrenheit')
Test =
50
So it works! I’ll leave the rest of the typing to you.
  1 个评论
Image Analyst
Image Analyst 2016-8-7
I'd to it slightly different
if strcmpi(unitFrom, Celsius) && strcmpi(unitTo, Fahrenheit)
Another thing missing is comments. Where are your comments? All good code has comments. Also you need to define a default value for T to make your code robust, even if it's an error value like -999. What if, due to an error in your program, none of the if conditions are met? It would throw and unhandled error. What if the user inputs 'zzzzz'? It would throw a messy cryptic error. Good code anticipates dumb users and tries to handle user errors, alerting them if needed. Don't just let it barf a bunch of cryptic red text all over the command window. Use sprintf(), uiwait(), and warndlg() to tell them that they entered some illegal units.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by