Programming Fundamentals/Conditions/C++
Appearance
conditions.cpp
[edit | edit source]// This program asks the user to select Fahrenheit or Celsius conversion
// and input a given temperature. Then the program converts the given
// temperature and displays the result.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://en.wikibooks.org/wiki/C%2B%2B_Programming
#include <iostream>
using namespace std;
double getTemperature(string label);
double calculateCelsius(double fahrenheit);
double calculateFahrenheit(double celsius);
void displayResult(double temperature, string fromLabel, double result, string toLabel);
int main() {
// main could either be an if-else structure or a switch-case structure
char choice;
double temperature;
double result;
cout << "Enter F to convert to Fahrenheit or C to convert to Celsius:" << endl;
cin >> choice;
// if-else approach
if (choice == 'C' || choice == 'c') {
temperature = getTemperature("Fahrenheit");
result = calculateCelsius(temperature);
displayResult(temperature, "Fahrenheit", result, "Celsius");
}
else if (choice == 'F' || choice == 'f') {
temperature = getTemperature("Celsius");
result = calculateFahrenheit(temperature);
displayResult(temperature, "Celsius", result, "Fahrenheit");
}
else {
cout << "You must enter C to convert to Celsius or F to convert to Fahrenheit!" << endl;
}
// switch-case approach
switch(choice) {
case 'C':
case 'c':
temperature = getTemperature("Fahrenheit");
result = calculateCelsius(temperature);
displayResult(temperature, "Fahrenheit", result, "Celsius");
break;
case 'F':
case 'f':
temperature = getTemperature("Celsius");
result = calculateFahrenheit(temperature);
displayResult(temperature, "Celsius", result, "Fahrenheit");
break;
default:
cout << "You must enter C to convert to Celsius or F to convert to Fahrenheit!" << endl;
}
}
double getTemperature(string label) {
double temperature;
cout << "Enter " << label << " temperature:" << endl;
cin >> temperature;
return temperature;
}
double calculateCelsius(double fahrenheit) {
double celsius;
celsius = (fahrenheit - 32) * 5 / 9;
return celsius;
}
double calculateFahrenheit(double celsius) {
double fahrenheit;
fahrenheit = celsius * 9 / 5 + 32;
return fahrenheit;
}
void displayResult(double temperature, string fromLabel, double result, string toLabel) {
cout << temperature << "° " << fromLabel << " is " << result << "° " << toLabel << endl;
}
Try It
[edit | edit source]Copy and paste the code above into one of the following free online development environments or use your own C++ compiler / interpreter / IDE.