So far, you have learned how to use
if-else
statements to execute one of two embedded
computation-performing
statements. You should also know about C++'s
conditional operator, which enables you to compute a value
from one of two embedded, value-producing expressions.
The conditional operator sees frequent service in output statements, where it helps you to produce the proper singularplural distinctions. Consider, for example, the following program, which displays a temperature change:
#includemain ( ) { int change; cin >> change; if (change == 1) cout << "The temperature has changed by " << change << " degree." << endl; else cout << "The temperature has changed by " << change << " degrees." << endl; } --- Data --- 1 --- Result --- The temperature has changed by 1 degree.
The program works, but most C++ programmers would be unhappy because there are two separate output statements that are almost identical. Such duplication makes programs longer, and the longer a program is, the greater the chance that a bug will creep in.
Accordingly, it would be better to move the variationthe part that produces either the word degree or the word degreesinto a value-producing expression inside a single output statement.