Need help with homework.

조회 수: 1 (최근 30일)
Toby
Toby 2024년 7월 26일
답변: Steven Lord 2024년 7월 26일
This is only my first couple of days using MATLAB. Basically I am trying to make a little temperature conversion program however the displayed answer is always in the form of a 1 x 2 matrix. Any advice is appreciated.
% prompt for user to choose which conversion
chosen_temp = input('What is ur chosen conversion, Celsius to Farenheit (1) or Farenheit to Celsius (2): ','s');
% using that answer to determine which formula is needed and then the
% converted answer
switch chosen_temp
case '1'
disp('Celsius to Farenheit')
initial_temp = input('Enter the temperature you would like to convert in Celsius:', 's');
temperature = initial_temp * 9 / 5 + 32
case '2'
disp('Farenheit to Celsius')
initial_temp = input('Enter the temperature you would like to convert in Farenheit:', 's');
temperature = (initial_temp - 32) * (5 / 9)
end

채택된 답변

Steven Lord
Steven Lord 2024년 7월 26일
When you call the input function with 's' as the last input, that function will return what you enter as text not as numbers. So if you had entered the number 42 at that prompt, what you would have received is actually:
initial_temp = '42'
initial_temp = '42'
When you perform arithmetic on a char vector, MATLAB will convert the individual characters into their ASCII codes and perform the arithmetic on those ASCII values.
T = initial_temp + 1 % not 43 but the ASCII values for '4' and '2' incremented by 1
T = 1x2
53 51
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
char(T) % '53'
ans = '53'
If you omit the 's' then initial_temp would be a number.
initial_temp = 42

추가 답변 (1개)

Torsten
Torsten 2024년 7월 26일
Note that the name of the German physician was Fahrenheit, not Farenheit.
% prompt for user to choose which conversion
chosen_temp = 1;%input('What is ur chosen conversion, Celsius to Farenheit (1) or Farenheit to Celsius (2): ','s');
% using that answer to determine which formula is needed and then the
% converted answer
switch chosen_temp
case 1
disp('Celsius to Farenheit')
initial_temp = 435;%input('Enter the temperature you would like to convert in Celsius:', 's');
temperature = initial_temp * 9 / 5 + 32;
case 2
disp('Farenheit to Celsius')
initial_temp = 376;%input('Enter the temperature you would like to convert in Farenheit:', 's');
temperature = (initial_temp - 32) * (5 / 9);
end
Celsius to Farenheit
temperature
temperature = 815

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by