Need help with homework.

3 次查看(过去 30 天)
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