Convert Fahrenheit to Celsius in C++
Convert a Fahrenheit temperature to Celsius in C++ with C = (F - 32) * 5 / 9. Shows why 5 / 9 is 0 in integer math and why the parentheses must stay.
1#include <iostream>2#include <iomanip>3using namespace std;45int main() {6 float fahrenheit, celsius;78 cout << "Enter temperature in Fahrenheit: ";9 cin >> fahrenheit;1011 // Formula: C = (F - 32) * 5/912 celsius = (fahrenheit - 32) * 5.0 / 9.0;1314 cout << fixed << setprecision(2);15 cout << fahrenheit << "°F = " << celsius << "°C" << endl;1617 return 0;18}
Sample Output
98.60°F = 37.00°C
Input and result, both shown with two decimals.
In this one
- How to turn a formula into a C++ expression
- Why integer 5 / 9 gives 0
- How operator precedence changes a formula
- How to sanity-check a conversion with known values
How it works
- 1
Read fahrenheit as a float (98.6 in the sample).
- 2
Subtract 32 inside the parentheses first: 66.6.
- 3
Multiply by 5.0 and divide by 9.0: 37.0.
- 4
Set fixed and setprecision(2).
- 5
Print 98.60°F = 37.00°C.
Edge cases
Integer division
Write celsius = (fahrenheit - 32) * (5 / 9);
5 / 9 is integer division and gives 0, so every result is 0.00. Writing 5.0 / 9.0 keeps the fraction.
Degree symbol looks broken
The ° character prints as strange symbols.
° is not plain ASCII. Some Windows consoles use a different code page, so the bytes show as junk. Printing "F" and "C" without the symbol avoids it.
What's going on
This C++ program converts Fahrenheit to Celsius with (F - 32) * 5 / 9.
#include <iomanip>
For fixed and setprecision. Same trap as float multiplication.
float fahrenheit, celsius;
Temperature is not an integer unless you want 98°F to become 37 with no tenths.
cin >> fahrenheit;
Sample uses 98.6.
celsius = (fahrenheit - 32) * 5.0 / 9.0;
The .0 is load-bearing. 5 / 9 with integers is 0 in C++. Then every result is 0. 5.0 / 9 or 5.0 / 9.0 both work because one side is floating.
Parentheses: subtract 32 first. (F - 32) * 5 / 9, not F - 32 * 5 / 9. Without parens, 32 * 5 / 9 happens first and 98.6 becomes something near 81.
Checks:
If you get something near 17, the 32 wasn't subtracted. If you get 0, integer division ate the fraction.
cout << fixed << setprecision(2); then prints both scales with two digits after the dot.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does (98.6 - 32) * 5 / 9 evaluate to in C++?
Pick an answer to check it.
Question 2
Why are the parentheses around (F - 32) needed?
Pick an answer to check it.
Questions people ask
How do I convert Celsius back to Fahrenheit?
F = C * 9.0 / 5.0 + 32. For 37 that gives 98.6.
Can I use int for temperatures?
Only if you accept losing the decimal part. 98.6 would be read as 98 and the answer would be off.
At what value are Fahrenheit and Celsius equal?
At -40. Plug it in: (-40 - 32) * 5 / 9 = -40.