3.4.4. temp.cpp (switch Version)

Time: 00:08:13 | Download: Large, Large (CC) Small | Streaming, Streaming (CC)

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.

\[c = {5 \over 9} (f - 32) \] \[f = {9 \over 5} c + 32 \]
Fahrenheit to Celsius and Celsius to Fahrenheit. Formulas to convert from one temperature scale to the other. The example converts the formulas to C++ expressions.

Test Cases

Scale Freezing Boiling
Fahrenheit 32 212
Celsius 0 100

Program

#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 example: temp.cpp. Switch-based temperature conversion program. A 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 >.
  1. The switch statement evaluates the expression and begins the search for a match, searching the switch from top to bottom.
  2. Two adjacent cases without code between them are conveniently interpreted as a single logical-OR operation.
  3. The braces following the cases create two new scopes, so double f; and double c; are defined in different scopes.
  4. The default case runs if none of the other cases match the switch expression.