Filter löschen
Filter löschen

Temperature conversion what does this code lack?

1 Ansicht (letzte 30 Tage)
Sandie Nhatien Vu
Sandie Nhatien Vu am 7 Aug. 2016
Kommentiert: Image Analyst am 7 Aug. 2016
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.

Antworten (1)

Star Strider
Star Strider am 7 Aug. 2016
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 Kommentar
Image Analyst
Image Analyst am 7 Aug. 2016
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by