Convert Celsius to Fahrenheit in C++
Learn how to build a Celsius to Fahrenheit converter in C++. This exercise is perfect for mastering floating-point variables, mathematical formulas, and user interaction through the console.
Understanding the Conversion Logic
Double Data Type
We use double instead of int to handle decimal points, ensuring precision during temperature calculations.
Conversion Formula
The logic follows the standard formula: (Celsius × 9/5) + 32. C++ processes this using operator precedence.
Formatted Output
Using cout, we concatenate strings and variables to display a clear, human-readable result in Fahrenheit.
Pro Tip: Order of Operations
In C++, multiplication and division happen before addition. Using parentheses (celsius * 9 / 5) makes your code easier for others to read and maintain.
Core Programming Concepts:
- Floating-point: Handling decimals with
double. - Math Expressions: Applying algebraic formulas in code.
- Console I/O: Interactive input and output streams.
Learning Objectives
- Declare
doublevariables for decimal precision. - Capture temperature input using
cin. - Translate a mathematical formula into C++ syntax.
- Display the converted Fahrenheit result.
C++ Source Code: Celsius to Fahrenheit
#include <iostream>
using namespace std;
int main() {
double celsius, fahrenheit;
// Prompt user for input
cout << "Enter temperature in Celsius: ";
cin >> celsius;
// Apply the conversion formula
fahrenheit = (celsius * 9 / 5) + 32;
// Output the result
cout << "Temperature in Fahrenheit: " << fahrenheit << endl;
return 0;
}
Program Console Output:
Enter temperature in Celsius: 25
Temperature in Fahrenheit: 77