Why my code miscalculates conversions?

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}])

 采纳的回答

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 个评论

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.
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.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Programming 的更多信息

产品

版本

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by