Need help with homework.

1 Ansicht (letzte 30 Tage)
Toby
Toby am 26 Jul. 2024
Beantwortet: Steven Lord am 26 Jul. 2024
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

Akzeptierte Antwort

Steven Lord
Steven Lord am 26 Jul. 2024
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

Weitere Antworten (1)

Torsten
Torsten am 26 Jul. 2024
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

Kategorien

Mehr zu General Physics finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by