|
|
|
|
|
|
|
In Chapter 2, we introduced the elements of the C++ language and discussed how to construct and run very simple programs. In this chapter we revisit two topics in greater depth: writing arithmetic expressions and formatting the output to make it informative and easy to read. We also show how to make programs more powerful by using library functions-prewritten functions that are part of every C++ system and are available for use by any program. |
|
|
|
|
|
|
|
|
The expressions we've used so far have contained at most a single arithmetic operator. We also have been careful not to mix values of different data types in an expression. Now we look at more complicated expressions-ones that are composed of several operators and ones that contain mixed data types. |
|
|
|
|
|
|
|
|
Arithmetic expressions can be made up of many constants, variables, operators, and parentheses. In what order are the operations performed? For example, in the assignment statement |
|
|
|
|
|
|
|
|
avgTemp = FREEZE_PT + BOIL_PT / 2.0; |
|
|
|
|
|
|
|
|
is FREEZE_PT + BOIL_PT calculated first or is BOIL_PT / 2.0 calculated first? |
|
|
|
|
|
|
|
|
The five basic arithmetic operators (+ for addition, - for subtraction, * for multiplication, / for division, and % for modulus) and parentheses are ordered the same way mathematical operators are, according to precedence rules: |
|
|
|
|
|
|
|
|
In the example above, we divide BOlL_PT by 2.0 first and then add FREEZE_PT to the result. |
|
|
|
|
|
|
|
|
You can change the order of evaluation by using parentheses. In the statement |
|
|
|
|
|
|
|
|
avgTemp = (FREEZE_PT + BOIL_PT) / 2.0; |
|
|
|
|
|