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!