Why my code miscalculates conversions?
15 views (last 30 days)
Show older comments
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}])
0 Comments
Accepted Answer
Walter Roberson
on 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 Comments
Les Beckham
on 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.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!