Question:
What's wrong with my code?
2013-08-24 11:56:34 UTC
// Write a program that has main() call a user-defined function that takes a
// Celsius temperature value as an argument and then returns the equivalent
// Fahrenheit value. the program should request Celsius value as input from the
// user and display the result, as shown in the following code:

// Please enter a Celsius value: 20
// 20 degrees Celsius is 68 degrees Fahrenheit.
// For reference, here is the formula for making the conversion:

// Fahrenheit = 1.8 * degrees Celsius + 32

#include

using namespace std;

int main()
{
int cels, fahr;
fahr = (1.8 * cels) + 32;

cout << "Please enter a Celsius value: " << endl;
cin >> cels;

cout << cels << " degrees Celsius is " << fahr << " degrees Fahrenheit." << endl;

system("pause");
return 0;
}
Three answers:
daSVgrouch
2013-08-24 12:00:23 UTC
move fahr = 1.8 * cels + 32;

so that it follows cin >> cels;

change cels and fahr to float or double or the arithmetic won't work......



you said you wanted a function that would do the conversion.....



float convertToFahrenheit(float celsius)

{

return 1.8 * celsius + 32.0;

}
Ben
2013-08-24 19:02:06 UTC
Two things :



1)You're using integers, meaning any fraction of a degree will get cut off.



2) Putting an equation does not bind the equation to the value. It sets the value. Here's how your program works



* cels and fahr are some random number (say 0)

* you calculate fahr = (1.8 * cels) + 32, cels is 0 so fahr is now 32.

* you ask the user to enter cels. They enter "15". THIS DOES NOT CHANGE FAHR AT ALL.

* you print out "15 degrees Celsius is 32 degrees Fahrenheit".



You need to hold off on calculating fahr until after you've asked for cels.
Russell
2013-08-24 19:01:02 UTC
well you dont initialize cels before you add it to fahr, you need to cin >> cels before you do fahr = (1.8 * cels) + 32



also cin.get(); is better then system("pause")


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...