3.4.2. temp.cpp (if Version)

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

A program to convert a temperature from Fahrenheit to Celsius and from Celsius to Fahrenheit. The first version uses an if-else ladder to choose the initial and final temperature scales.

\[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";				// (a)
	cout << "C\tfor Celsius to Fahrenheit\n";

	cout << "Select: ";
	char	choice;

	cin >> choice;								// (b)
	cin.ignore();								// (c)

	if (choice == 'F' || choice == 'f')					// (d)
	{
		double	f;
		cout << "Please enter the temperature in Fahrenheit: ";
		cin >> f;

		cout << "Celsius: " << 5.0 / 9.0 * (f - 32) << endl;
	}
	else if (choice == 'C' || choice == 'c')
	{
		double	c;
		cout << "Please enter the temperature in Celsius: ";
		cin >> c;

		cout << "Fahrenheit: " << 9.0 / 5.0 * c + 32 << endl;
	}
	else
		cout << "Unrecognized choice: \"" << choice << "\"\n";

	return 0;								// (e)
}
temp.cpp. Programmers can inadvertently introduce subtle errors into programs when they convert formulas to C++ code. This example extends the ftoc.cpp program presented in the last chapter. Please review the errors described in the previous version.
  1. The program prints a menu of possible operations
  2. The user chooses by selecting "F," "f," "C," or "c" followed by pressing the "Enter" key, and the computer reads the choice
  3. The ignore function discards the new line character
  4. An if-else if-else statement selects the branch of code to execute
    1. The logical-OR operator, ||, allows the user to enter either an upper or lower case letter. Students often ask if it's possible to use a shortcut: choice == 'F' || 'f'. This expression fails because both the left- and right-hand operands must be complete Boolean-valued sub-expressions
    2. The braces create two new scopes; so double f; and double c; are not created in the same scope
    3. The correct prompt, data input, and conversion statement execute; the correct value is printed
  5. Returns an exit status: 0 indicates no errors