Convert Fahrenheit to Celsius in C++

Convert Fahrenheit to Celsius in C++. 5/9 as integers is 0 — use 5.0/9.0.

BeginnerBasic ProgramsExample 9 of 14
convert-fahrenheit-to-celsius.cpp
1#include <iostream>
2#include <iomanip>
3using namespace std;
4
5int main() {
6 float fahrenheit, celsius;
7
8 cout << "Enter temperature in Fahrenheit: ";
9 cin >> fahrenheit;
10
11 // Formula: C = (F - 32) * 5/9
12 celsius = (fahrenheit - 32) * 5.0 / 9.0;
13
14 cout << fixed << setprecision(2);
15 cout << fahrenheit << "°F = " << celsius << "°C" << endl;
16
17 return 0;
18}

Output

Enter temperature in Fahrenheit: 98.6
98.60°F = 37.00°C

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:

32°F → 0°C
212°F → 100°C
98.6°F → 37.00°C (the sample)

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.