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.
Scale | Freezing | Boiling |
---|---|---|
Fahrenheit | 32 | 212 |
Celsius | 0 | 100 |
#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) }
||
, 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-expressionsdouble f;
and double c;
are not created in the same scope