Why my code miscalculates conversions?
조회 수: 12 (최근 30일)
이전 댓글 표시
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
채택된 답변
Walter Roberson
2023년 4월 6일
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
Les Beckham
2023년 4월 6일
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.
추가 답변 (0개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!