Centigrade to Fahrenheit Converter doesn't work properly

8 vues (au cours des 30 derniers jours)
Laura
Laura le 25 Fév 2024
Commenté : Walter Roberson le 25 Fév 2024
I want to create a function to convert degrees Celsius to degrees Fahrenheit and return the result as the function output. When I input a number to convert the answer is the same number instead of the converted amount. For example, when I put 40 the answer is 40. It should be 104. How can I fix this?
function F = C2F(C)
C = input('Input the temperature in Celsius that you want to convert to Farenheit:');
F = 1.8*C + 32;
end

Réponse acceptée

VBBV
VBBV le 25 Fév 2024
C = 40; %input('Input the temperature in Celsius that you want to convert to Farenheit:');
C2F(C)
ans = 104
function F = C2F(C)
F = 1.8*C + 32;
end
  3 commentaires
Laura
Laura le 25 Fév 2024
Modifié(e) : Laura le 25 Fév 2024
I have changed the script to:
C2F()
function F = C2F()
C = input('Input the temperature in Celsius that you want to convert to Farenheit:');
F = 1.8*C + 32;
end
It converts the 40 to 104 but how can I get it to convert a negative number?
Walter Roberson
Walter Roberson le 25 Fév 2024
-40 C is famously -40 F .
-40 C is not -104 F . The conversion is not symmetric around 0.

Connectez-vous pour commenter.

Plus de réponses (1)

Sam Chak
Sam Chak le 25 Fév 2024
Hey @Laura, there doesn't seem to be any issue with the code when the input() command is placed outside of the C2F() function.
% C = input('Input the temperature in Celsius that you want to convert to Farenheit:');
C = 40;
F = C2F(C)
F = 104
function F = C2F(C)
F = 1.8*C + 32;
end
  2 commentaires
Laura
Laura le 25 Fév 2024
I would like to put in any amount to be converted, not only 40.
Stephen23
Stephen23 le 25 Fév 2024
Modifié(e) : Stephen23 le 25 Fév 2024
"I would like to put in any amount to be converted, not only 40."
You can use any input value you want, not only 40. Just like every other MATLAB function, when you define your own functions you can call them with any input values you want. In fact, that is rather the whole point of writing functions.
How exactly would MATLAB would stop you from calling your function with a value of 23.5 or -16 or 999?
This is the best approach. One day you will just have to unlearn using INPUT everywhere.

Connectez-vous pour commenter.

Catégories

En savoir plus sur DICOM Format dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by