Temperature conversion what does this code lack?
2 ビュー (過去 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.
0 件のコメント
回答 (1 件)
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
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 Center および File Exchange で Handle Classes についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!