Temperature conversion what does this code lack?

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일

0 개 추천

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

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.

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

카테고리

도움말 센터File Exchange에서 Simulink에 대해 자세히 알아보기

질문:

2016년 8월 7일

댓글:

2016년 8월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by