Convert Fahrenheit to Celsius in C++
Convert Fahrenheit to Celsius in C++. 5/9 as integers is 0 — use 5.0/9.0.
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}
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:
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.