There are four mistakes in your code.
1) The main point is to realise that the computer does things in the order you ask it to. Obviously the correct order is a) ask the user to enter a temperature b) convert it to celsius. But your code does it the other way round. Here's your code with some comments of mine
// convert fahrenheit to celcius
int celsius = 5/9*(fahrenheit-32);
// ask user to enter fahrenheit temperature
cout << "Please enter Fahrenheit degrees: ";
cin >> fahrenheit ;
Hopefully it's now obvious that you have things the wrong way round
2) Second error is that you have choen the wrong type for your variables. Temperature is not an integral quantity (nothing wrong with saying the temperature is 80.5 degrees for instance). So you should choose a floating point type for your variables, float
is one possibility.
3) Third error is quite technical but important to understand. In your equation you wrote 5/9
, both 5
and 9
are integers, so the computer is going to perform integer division, which means whatever the mathematical result of the division the computer is going to drop the fractional part of the result, leaving an integer. So mathematically 5/9
is 0.555555...
, droping the fractional part leaves 0
, so your equation is the same as 0*(fahrenheit-32)
which is obviously not going to give the right result. Use 5.0/9.0
instead of 5/9
that way you get floating point division.
4) Final error is quite trivial
cout.precision(0); //two decimal for cents
If you want two decimal places it should be
cout.precision(2);
Finally, its not an error, but the comments about money are inappropriate in a program about temperature.
Here's a version of your code with these errors fixed
int main() {
cout.setf(ios::fixed); //no scientific notation
cout.setf(ios::showpoint); //show decimal point
cout.precision(2); //two decimal places
float fahrenheit;
cout << "Please enter Fahrenheit degrees: ";
cin >> fahrenheit;
float celsius = 5.0/9.0*(fahrenheit-32.0);
cout << "Celsius: " << celsius << endl;
return 0;
}
I'm sure you're surprised that a short program can have so many mistakes. It just emphasises that you have to be careful and precise when you write code.