A program to convert a temperature from Fahrenheit to Celsius and from Celsius to Fahrenheit. Version 2 behaves like the previous temp.cpp, but a switch statement replaces the if-else ladder of the first version.
| Scale | Freezing | Boiling |
|---|---|---|
| Fahrenheit | 32 | 212 |
| Celsius | 0 | 100 |
#include <iostream>
using namespace std;
int main()
{
cout << "F\tfor Fahrenheit to Celsius\n";
cout << "C\tfor Celsius to Fahrenheit\n";
cout << "Select: ";
char choice;
cin >> choice;
cin.ignore();
switch (choice) // (a)
{
case 'F' : // (b)
case 'f' :
{ // (c)
double f;
cout << "Please enter the temperature in Fahrenheit: ";
cin >> f;
cout << "Celsius: " << 5.0 / 9.0 * (f - 32) << endl;
break;
}
case 'C' :
case 'c' :
{
double c;
cout << "Please enter the temperature in Celsius: ";
cin >> c;
cout << "Fahrenheit: " << 9.0 / 5.0 * c + 32 << endl;
break;
}
default : // (d)
cout << "Unrecognized choice: \"" << choice << "\"\n";
break;
}
return 0;
}
switch statement tests an integer-valued expression, usually a variable, choice in this example, for possible discrete values. For example, choice == 'F'. Switches don't support floating-point values or range tests with < or >.
switch statement evaluates the expression and begins the search for a match, searching the switch from top to bottom.double f; and double c; are defined in different scopes.default case runs if none of the other cases match the switch expression.