#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float fahrenheit, celsius;
cout << "Enter temperature in Fahrenheit: ";
cin >> fahrenheit;
// Formula: C = (F - 32) * 5/9
celsius = (fahrenheit - 32) * 5.0 / 9.0;
cout << fixed << setprecision(2);
cout << fahrenheit << "°F = " << celsius << "°C" << endl;
return 0;
}Output
Enter temperature in Fahrenheit: 98.6 98.60°F = 37.00°C
Convert Fahrenheit to Celsius in C++
This program helps you convert a temperature from Fahrenheit to Celsius. It uses a well-known formula from science and applies it using simple arithmetic in C++. The program also shows how to format decimal numbers so they look neat and easy to read.
1. Why Convert Fahrenheit to Celsius?
Temperature is measured differently in different places:
- The United States mostly uses Fahrenheit (°F)
- Most other countries use Celsius (°C)
This program teaches how to convert between the two using math.
2. Header Files
The program uses two headers:
-
#include <iostream>
Allows us to use cin (input) and cout (output). -
#include <iomanip>
Provides tools like fixed and setprecision() to control how decimal numbers are printed.
3. Declaring Float Variables
We use:
float fahrenheit, celsius;
- fahrenheit → stores the temperature entered by the user
- celsius → stores the converted temperature
We use float because temperature often includes decimal values (e.g., 98.6°F).
4. Taking Input From the User
The program displays:
cout << "Enter temperature in Fahrenheit: ";
cin >> fahrenheit;
Whatever the user types (like 98.6) is stored in the variable fahrenheit.
5. The Conversion Formula
The conversion formula is:
C = (F - 32) × 5/9
This formula converts a temperature from the Fahrenheit scale to the Celsius scale.
In the program:
celsius = (fahrenheit - 32) * 5.0 / 9.0;
Here's why we use ## 5.0 / 9.0 instead of 5 / 9:
- 5 / 9 (without decimal) would perform integer division → result = 0
- 5.0 / 9.0 performs floating-point division → correct result ≈ 0.5555
So 5.0 and 9.0 ensure accurate decimal calculations.
6. Formatting the Decimal Output
Before printing the final result, the program uses:
cout << fixed << setprecision(2);
This means:
- fixed → show numbers in normal decimal form
- setprecision(2) → show exactly 2 decimal places
So:
- 98.6 becomes 98.60
- 37 becomes 37.00
This makes the output clean and professional.
7. Displaying the Result
The output is printed as:
cout << fahrenheit << "°F = " << celsius << "°C" << endl;
If the user enters 98.6, the program prints:
98.60°F = 37.00°C
Summary
- The program reads a temperature in Fahrenheit.
- It converts it to Celsius using the formula C = (F - 32) × 5/9.
- Floating-point numbers ensure accurate calculations.
- setprecision(2) formats the output to two decimal places.
- This is a simple and practical program used in many real-world applications.
This example helps build confidence with arithmetic, formulas, and formatted output in C++.