Why my code miscalculates conversions?

13 Ansichten (letzte 30 Tage)
Emir
Emir am 6 Apr. 2023
Kommentiert: Emir am 6 Apr. 2023
You can see my progress below. I'm so confused because when I try to calculate 0C to K, my code perfectly calculates 1F to K. I couldn't check other wrong answers but probably I messed up those if/elseif statements. I'm not looking for the working code so study sources are welcome too.
prompt={'Enter temperature','Enter unit of temperature (C, F or K)','Enter unit of temperature wanted (C, F or K'};
dlgtitle='Temperature Converter CFK';
dims = [1 1 1];
user_input=inputdlg(prompt,dlgtitle,dims);
if strcmp(user_input{2},'C')
t1= str2double(user_input{1});
elseif strcmp(user_input{3},'F')
t1f=((t1*(9/5))+32);
end
if strcmp(user_input{2},'C')
t1= str2double(user_input{1});
elseif strcmp(user_input{3},'K')
t1f=(t1+273.15);
end
if strcmp(user_input{2},'F')
t1= str2double(user_input{1});
elseif strcmp(user_input{3},'C')
t1f=((t1-32)*(5/9));
end
if strcmp(user_input{2},'F')
t1= str2double(user_input{1});
elseif strcmp(user_input{3},'K')
t1f=(((t1-32)*(5/9))+273.15);
end
if strcmp(user_input{2},'K')
t1= str2double(user_input{1});
elseif strcmp(user_input{3},'C')
t1f=(t1-273.15);
end
if strcmp(user_input{2},'K')
t1= str2double(user_input{1});
elseif strcmp(user_input{3},'F')
t1f=(((t1-273.15)*(9/5))+32);
end
msgbox ([num2str(t1f) , user_input{3}])

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 6 Apr. 2023
if strcmp(user_input{2},'C')
t1= str2double(user_input{1});
That statement is executed any time the second input is 'C'
elseif strcmp(user_input{3},'F')
t1f=((t1*(9/5))+32);
That statement is only executed if the second input is not C but the third input is F
You want more like
if strcmp(user_input{2},'C') && strcmp(user_input{3},'F')
  2 Kommentare
Les Beckham
Les Beckham am 6 Apr. 2023
Yes. And this line should appear only once above the if tests:
t1= str2double(user_input{1});
with only t1f being calculated inside the if tests.
Emir
Emir am 6 Apr. 2023
Thank you both for your answers. Mr. Robertson's answer solved my issue. Mr. Beckham your notification probably saved me a couple points because it was already like what you suggest, but I made it up like this while trying to bugfix the code. I'll send this page's link to my professor to let him know how I solved the bug which I informed earlier.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Produkte


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by