Computer Programming/Conditions/C++

From Wikiversity
Jump to: navigation, search

conditions.cpp[edit]

// 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.

#include <iostream>

using namespace std;

void ifElse();
void switchCase();
void toCelsius();
void toFahrenheit();

int main()
{
    ifElse();
    switchCase();
}

void ifElse()
{
    char choice;
    
    cout << "Enter F to convert to Fahrenheit or C to convert to Celsius:" << endl;
    cin >> choice;
    if (choice == 'C' || choice == 'c')
    {
        toCelsius();
    }
    else if (choice == 'F' || choice == 'f')
    {
        toFahrenheit();
    }
    else
    {
        cout << "You must enter C to convert to Celsius or F to convert to Fahrenheit!" << endl;
    }
}

void switchCase()
{
    char choice;
    
    cout << "Enter F to convert to Fahrenheit or C to convert to Celsius:" << endl;
    cin >> choice;
    switch(choice)
    {
        case 'C':
        case 'c':
            toCelsius();
            break;
        case 'F':
        case 'f':
            toFahrenheit();
            break;
        default:
            cout << "You must enter C to convert to Celsius or F to convert to Fahrenheit!" << endl;
    }
}

void toCelsius()
{
    double f;
    double c;
    
    cout << "Enter Fahrenheit temperature:" << endl;
    cin >> f;
    c = (f - 32) * 5 / 9;
    cout << f << "° Fahrenheit is " << c << "° Celsius" << endl;
}

void toFahrenheit()
{
    double c;
    double f;
    
    cout << "Enter Celsius temperature:" << endl;
    cin >> c;
    f = c * 9 / 5 + 32;
    cout << c << "° Celsius is " << f << "° Fahrenheit" << endl;
}

Try It[edit]

Copy and paste the code above into one of the following free online development environments or use your own C++ compiler / interpreter / IDE.

See Also[edit]