1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
#include <iostream> using namespace std; // Function to convert Celsius to Fahrenheit double celsiusToFahrenheit(double celsius) { return (celsius * 9.0 / 5.0) + 32.0; } // Function to convert Fahrenheit to Celsius double fahrenheitToCelsius(double fahrenheit) { return (fahrenheit - 32.0) * 5.0 / 9.0; } int main() { int choice; double temperature, convertedTemperature; cout << "Temperature Converter" << endl; cout << "1. Celsius to Fahrenheit" << endl; cout << "2. Fahrenheit to Celsius" << endl; cout << "Choose an option (1 or 2): "; cin >> choice; if (choice == 1) { cout << "Enter temperature in Celsius: "; cin >> temperature; convertedTemperature = celsiusToFahrenheit(temperature); cout << "Temperature in Fahrenheit: " << convertedTemperature << "°F" << endl; } else if (choice == 2) { cout << "Enter temperature in Fahrenheit: "; cin >> temperature; convertedTemperature = fahrenheitToCelsius(temperature); cout << "Temperature in Celsius: " << convertedTemperature << "°C" << endl; } else { cout << "Invalid option!" << endl; } return 0; } |
Explanation
- Temperature Conversion Functions:
celsiusToFahrenheit(double celsius)
: This function converts a temperature from Celsius to FahrenheitfahrenheitToCelsius(double fahrenheit)
: This function converts a temperature from Fahrenheit to Celsius
Advertisement - Main Function:
- The
main()
function starts by presenting the user with two options: converting from Celsius to Fahrenheit or from Fahrenheit to Celsius. - The user is prompted to enter their choice (
1
or2
). - Depending on the choice, the program asks for the input temperature, performs the conversion using the appropriate function, and then displays the converted temperature.
- If the user enters an invalid option, an error message is displayed.
Advertisement - The