Introduction
Temperature conversion is an essential concept in science and daily life. Different countries use different temperature scales to measure temperature, with Celsius and Fahrenheit being the most widely used scales.
The objective of this program is to convert temperatures between the two scales: Celsius and Fahrenheit. It allows the user to enter a temperature and select whether they want to convert from Celsius to Fahrenheit or from Fahrenheit to Celsius.
Program Code
#include using namespace std; int main() { float temp, convertedTemp; int choice; cout << "Temperature Converter\n"; cout << "Choose the conversion:\n"; cout << "1. Celsius to Fahrenheit\n"; cout << "2. Fahrenheit to Celsius\n"; cout << "Enter your choice (1 or 2): "; cin >> choice; // Celsius to Fahrenheit if (choice == 1) { cout << "Enter temperature in Celsius: "; cin >> temp; convertedTemp = (temp * 9/5) + 32; cout << temp << " Celsius is equal to " << convertedTemp << " Fahrenheit.\n"; } // Fahrenheit to Celsius else if (choice == 2) { cout << "Enter temperature in Fahrenheit: "; cin >> temp; convertedTemp = (temp - 32) * 5/9; cout << temp << " Fahrenheit is equal to " << convertedTemp << " Celsius.\n"; } else { cout << "Invalid choice! Please select 1 or 2.\n"; } return 0; }
Program Explanation
This program allows the user to convert temperatures between Celsius and Fahrenheit. The program works as follows:
-
- The program starts by displaying a menu, asking the user to select the type of conversion (Celsius to Fahrenheit or Fahrenheit to Celsius).
- Based on the user’s choice, the program prompts the user to enter a temperature in either Celsius or Fahrenheit.
- If the user selects ‘1’, the program converts the entered Celsius temperature to Fahrenheit using the formula:
(Celsius * 9/5) + 32 = Fahrenheit
-
- If the user selects ‘2’, the program converts the entered Fahrenheit temperature to Celsius using the formula:
(Fahrenheit - 32) * 5/9 = Celsius
- The program then displays the converted temperature to the user.
- If the user enters an invalid choice, the program notifies them and exits.
How to Run the Program
To run this program, follow these steps:
-
- Open a C++ development environment (IDE) like Code::Blocks, Dev-C++, or any text editor and a C++ compiler such as GCC or Clang.
- Copy the provided C++ code into a new source file (e.g., temp_converter.cpp).
- Compile the program. If using GCC, run the following command in the terminal:
g++ temp_converter.cpp -o temp_converter
-
- Run the compiled program. If using GCC, execute it like this:
./temp_converter
- Follow the on-screen instructions to select a conversion type and input the temperature you want to convert.