Why my code miscalculates conversions?

조회 수: 12 (최근 30일)
Emir
Emir 2023년 4월 6일
댓글: Emir 2023년 4월 6일
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}])

채택된 답변

Walter Roberson
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
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.
Emir
Emir 2023년 4월 6일
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개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by