C++’s Primary Mat h Operators - 图1

Part I I

Using C++ Operators

C++’s Primary Mat h Operators - 图2

C++’s Primary Mat h Operators - 图3Using C++ Mat h Operators an d Precedence

If you are dreading this chapter because you don’t like math—relax, C++ does all your math for you! It is a misconception that you have to be good at math to understand how to program computers. In fact, programming practice assumes the opposite is true! Your computer is your “slave,” to follow your instructions, and to do all the calculations for you. This chapter explains how C++ computes by introducing you to

  • Primary math operators

  • Order of operator precedence

  • Assignment statements

  • Mixed data type calculations

  • Type casting

Many people who dislike math actually enjoy learning how the computer handles it. After learning the math operators and a few simple ways in which C++ uses them, you should feel comfortable using calculations in your programs. Computers are fast, and they can perform math operations much faster than you can!

C++’s Primary Mat h Operators

A C++ math operator is a symbol used for adding, subtracting, multiplying, dividing, and other operations. C++ operators are not always mathematical in nature, but many are. Table 8.1 lists these operator symbols and their primary meanings.

Table 8.1. C++ primary operators.

Symbol Meaning

* Multiplication

/ Division and Integer Division

% Modulus or Remainder

+ Addition

- Subtraction

Most of these operators work in the familiar way you expect them to. Multiplication, addition, and subtraction produce the same results (and the division operator usually does) as those produced with a calculator. Table 8.2 illustrates four of these simple operators.

Table 8.2. Typical operator results.

Formula

Result

4 * 2

8

64 / 4

16

80 - 15

65

12 + 9

21

Table 8.2 contains examples of binary operations performed with the four operators. Don’t confuse binary operations with binary numbers. When an operator is used between two literals, variables, or a combination of both, it is called a binary operator because it operates using two values. When you use these operators (when assigning their results to variables, for example), it does not matter in C++ whether you add spaces to the operators or not.

C++’s Primary Mat h Operators - 图4

The Unary Operator s

C++’s Primary Mat h Operators - 图5A unary operator operates on, or affects, a single value. For instance, you can assign a variable a positive or negative number by using a unary + or –.

Examples

  1. C++’s Primary Mat h Operators - 图6The following

    section of code assigns four variables a posi- tive or a negative number. The plus and minus signs are all unary because they are not used between two values.

The variable a is assigned a negative 25 value. The variable b is assigned a positive 25 value. The variable c is assigned a negative a value. The variable d is assigned a positive b value.

a = - 25; / / Assi gn ‘ a’ a negat i ve 25.

b = +25; / / Assi gn ‘ b’ a posi t i ve 25 ( + i s not needed) . c = - a; / / Assi gn ‘ c’ t he negat i ve of ‘ a’ (- 25) .

d = +b; / / Assi gn ‘ d’ t he posi t i ve of ‘ b’ ( 25, + not needed) .

  1. C++’s Primary Mat h Operators - 图7You

    generally do not have to use the unary plus sign. C++ assumes a number or variable is positive, even if it has no plus sign. The following four statements are equivalent to the previous four, except they do not contain plus signs.

a = - 25; / / Assi gn ‘ a’ a negat i ve 25. b = 25; / / Assi gn ‘ b’ a posi t i ve 25.

C++’s Primary Mat h Operators - 图8c = - a; / / Assi gn ‘ c’ t he negat i ve of ‘ a’ (- 25) . d = b; / / Assi gn ‘ d’ t he posi t i ve of ‘ b’ ( 25) .

  1. The unary negative comes in handy when you want to negate a single

    number or variable. The negative of a nega- tive is positive. Therefore, the following short program assigns a negative number (using the unary –) to a variable, then prints the negative of that same variable. Because it had a negative number to begin with, the cout produces a posi- tive result.

/ / Fil ename: C8NEG. CPP

/ / The negat i ve of a var i abl e t hat cont ai ns a negat i ve val ue. #i ncl ude <i ost r eam. h>

mai n( )

{

si gned i nt t emp=- 12; / / ‘ si gned’ i s not needed because

/ / i t i s t he def aul t. cout << - t emp << “ \ n” ; / / Pr oduces a 12 on- scr een.

r et ur n 0;

}

The variable declaration does not need the signed prefix, because all integer variables are signed by default.

  1. If you want to subtract the negative of a variable, make sure you

    put a space before the unary minus sign. For example, the following line:

new_t emp + new_t emp- - i nver si on_f act or ;

temporarily negates the i nver si on_f act or and subtracts that negated value from new_t emp .

The modulus%() computes remainders in division.

C++’s Primary Mat h Operators - 图9

Division and Modulu s

The division sign, / , and the modulus operator, %, might behave in ways unfamiliar to you. They’re as easy to use, however, as the other operators you have just seen.

The forward slash (/ ) is always used for division. However, it produces an integer called di vi de if integer values (literals, variables, or a combination of both) appear on both sides of the slash. If there is a remainder, C++ discards it.

The percent sign (%) produces a modulus, or a remainder, of an integer division. It requires that integers be on both sides of the symbol, or it does not work.

Examples

  1. C++’s Primary Mat h Operators - 图10Suppose

    you want to compute your weekly pay. The follow- ing program asks for your yearly pay, divides it by 52, and prints the results to two decimal places.

/ / Fil ename: C8DI V. CPP

C++’s Primary Mat h Operators - 图11/ / Di spl ays user ’ s weekl y pay. #i ncl ude <st di o. h>

mai n( )

{

f l oat weekl y, year l y;

pr i ntf (“ What i s your annual pay? “) ; / / Pr ompt user . scanf (“%f ” , &year l y) ;

weekl y = year l y/ 52; / / Comput es t he weekl y pay. pr i ntf (“ \
n\ nYour weekl y pay i s $%. 2f ” , weekl y) ;

r et ur n 0;

}

Because a floating-point number is used in the division, C++ produces a floating-point result. Here is a sample output from such a program:

What i s your annual pay? 38000. 00 Your weekl y pay i s $730. 77

Because this program used scanf () and pr i ntf () (to keep you familiar with both ways of performing input and output), the stdio.h header file is included rather than iostream.h.

  1. C++’s Primary Mat h Operators - 图12Integer

    division does not round its results. If you divide two integers and the answer is not a whole number, C++ ignores the fractional part. The following pr i ntf () s help show this. The output that results from each pr i ntf () appears in the comment to the right of each line.

pr i ntf (“ %d \ n” , 10/ 2) ; / / 5 ( no r emai nder) pr i ntf (“ %d \ n” , 300/ 100) ; / / 3 ( no r emai nder)

pr i ntf (“ %d \ n” , 10/ 3) ; / / 3 ( di scar ded r emai nder) pr i ntf (“ %d \ n” , 300/ 165) ; / / 1 ( di scar ded r emai nder)

C++ performs multiplication, division, and modulusbefore addition and subtraction.

The Order of Precedenc e

Understanding the math operators is the first of two steps toward understanding C++ calculations. You must also understand the order of precedence. The order of precedence (sometimes called the math hierarchy or order of operators) determines exactly how C++ computes formulas. The precedence of operators is exactly the same concept you learned in high school algebra courses. (Don’t worry, this is the easy part of algebra!) To see how the order of precedence works, try to determine the result of the following simple calculation:

2 + 3 * 2

If you said 10, you are not alone; many people respond with 10. However, 10 is correct only if you interpret the formula from the left. What if you calculated the multiplication first? If you took the value of 3 * 2 and got an answer of 6, then added the 2, you receive an answer of 8—which is exactly the same answer that C++ computes (and happens to be the correct way)!

C++ always performs multiplication, division, and modulus first, then addition and subtraction. Table 8.3 shows the order of the operators you have seen so far. Of course, there are many more levels to C++’s precedence table of operators than the ones shown in Table 8.3. Unlike most computer languages, C++ has 20 levels of precedence. Appendix D, “C++ Precedence Table,” contains the complete precedence table. Notice in this appendix that multiplica- tion, division, and modulus reside on level 8, one level higher than

level 9’s addition and subtraction. In the next few chapters, you learn how to use the remainder of this precedence table in your C++ programs.

Table 8.3. Order of precedence for primary operators.

Order Operator

First Multiplication, division, modulus remainder (* , / , %) Second Addition, subtraction (+, - )

Examples

  1. C++’s Primary Mat h Operators - 图13C++’s Primary Mat h Operators - 图14It

    is easy to follow C++’s order of operators if you follow the intermediate results one at a time. The three calculations in Figure 8.1 show you how to do this.

C++’s Primary Mat h Operators - 图15C++’s Primary Mat h Operators - 图16C++’s Primary Mat h Operators - 图17C++’s Primary Mat h Operators - 图18

/

C++’s Primary Mat h Operators - 图19

/

C++’s Primary Mat h Operators - 图20

C++’s Primary Mat h Operators - 图21C++’s Primary Mat h Operators - 图22

C++’s Primary Mat h Operators - 图23

Figure 8.1. C++’s order of operators with lines indicating precedence.

  1. C++’s Primary Mat h Operators - 图24Looking

    back at the order of precedence table, you might notice that multiplication, division, and modulus are on the same level. This implies there is no hierarchy on that level. If more than one of these operators appear in a calculation, C++ performs the math from the left. The same is true of addition and subtraction— C++ performs the operation on the extreme left first.

C++’s Primary Mat h Operators - 图25C++’s Primary Mat h Operators - 图26Figure 8.2 illustrates an example showing this process.

Figure 8.2. C++’s order of operators from the left, with lines indicating precedence.

Because the division appears to the left of the multiplication, it is computed first.

You now should be able to follow the order of these C++ operators. You don’t have to worry about the math because C++ does the actual work. However, you should understand this order of operators so you know how to structure your calculations. Now that you have mastered this order, it’s time to learn how you can override it with parentheses!

Using Parenthese s

If you want to override the order of precedence, you can add parentheses to the calculation. The parentheses actually reside on a level above the multiplication, division, and modulus in the prece- dence table. In other words, any calculation in parentheses—whether it is addition, subtraction, division, or whatever—is always calcu- lated before the rest of the line. The other calculations are then performed in their normal operator order.

Parentheses override the usual order of math.

The first formula in this chapter, 2 + 3 * 2 , produced an 8 because the multiplication was performed before addition. However, by adding parentheses around the addition, as in (2 + 3) * 2 , the answer becomes 10.

In the precedence table shown in Appendix D, “C++ Prece- dence Table,” the parentheses reside on level 3. Because they are higher than the other levels, the parentheses take precedence over multiplication, division, and all other operators.

C++’s Primary Mat h Operators - 图27C++’s Primary Mat h Operators - 图28C++’s Primary Mat h Operators - 图29

Examples

  1. C++’s Primary Mat h Operators - 图30C++’s Primary Mat h Operators - 图31C++’s Primary Mat h Operators - 图32C++’s Primary Mat h Operators - 图33C++’s Primary Mat h Operators - 图34The

    calculations shown in Figure 8.3 illustrate how paren- theses override the regular order of operators. These are the same three formulas shown in the previous section, but their results are calculated differently because the parentheses override the normal order of operators.

C++’s Primary Mat h Operators - 图35

3 * 4

/ 2 +

( 3

- 1)

3 * 4

/ 2 +

2

12

/ 2 +

2

6 +

2

8

20 /

( 3 + 5)

% 2

20 /

8 %

2

C++’s Primary Mat h Operators - 图36

C++’s Primary Mat h Operators - 图37C++’s Primary Mat h Operators - 图38C++’s Primary Mat h Operators - 图39Figure 8.3. Example of parentheses as the highest precedence level with lines indicating precedence.

  1. C++’s Primary Mat h Operators - 图40C++’s Primary Mat h Operators - 图41If

    an expression contains parentheses-within-parentheses, C++ evaluates the innermost parentheses first. The expres- sions in Figure 8.4 illustrate this.

C++’s Primary Mat h Operators - 图42

Figure 8.4. Precedence example of parentheses-within-parentheses with lines indicating precedence.

  1. C++’s Primary Mat h Operators - 图43C++’s Primary Mat h Operators - 图44The

    following program produces an incorrect result, even though it looks as if it will work. See if you can spot the error!

Comments to identify your program.

Include the header file iostream.h so cout works.

Declare the variables avg , gr ade1 , gr ade2 , and gr ade3 as floating- point variables.

The variable avg becomes equal to gr ade3 divided by 3.0 plus

gr ade2 plus gr ade1 .

Print to the screen The aver age i s and the average of the three grade variables.

Return to the operating system.

/ / Fil ename: C8AVG1. CPP

/ / Comput e t he aver age of t hr ee gr ades. #i ncl ude <i ost r eam. h>

mai n( )

{

f l oat avg, gr ade1, gr ade2, gr ade3;

gr ade1 = 87. 5;

gr ade2 = 92. 4;

gr ade3 = 79. 6;

avg = gr ade1 + gr ade2 + gr ade3 / 3. 0; cout << “ The aver age i s “ << avg << “ \ n” ; r et ur n 0;

}

The problem is that division is performed first. Therefore, the third grade is divided by 3.0 first, then the other two grades are added to that result. To correct this problem, you simply have to add one set of parentheses, as shown in the following:

/ / Fil ename: C8AVG2. CPP

/ / Comput e t he aver age of t hr ee gr ades. #i ncl ude <i ost r eam. h>

mai n( )

{

f l oat avg, gr ade1, gr ade2, gr ade3;

gr ade1 = 87. 5;

gr ade2 = 92. 4;

gr ade3 = 79. 6;

C++’s Primary Mat h Operators - 图45avg = ( gr ade1 + gr ade2 + gr ade3) / 3. 0; cout << “ The aver age i s “ << avg << “ \ n” ; r et ur n 0;

}

C++’s Primary Mat h Operators - 图46

Maintainability is the computer industry’s word for the chang- ing and updating of programs previously written in a simple style. The business world is changing rapidly, and the pro- grams companies have used for years must often be updated to reflect this changing environment. Businesses do not always have the resources to write programs from scratch, so they usually modify the ones they have.

Years ago when computer hardware was much more expen- sive, and when computer memories were much smaller, it was important to write small programs, which often meant relying on clever, individualized tricks and shortcuts. Unfortunately, such programs are often difficult to revise, especially if the original programmers leave and someone else (you!) must modify the original code.

Companies are realizing the importance of spending time to write programs that are easy to modify and that do not rely on tricks, or “quick and dirty” routines that are hard to follow. You can be a much more valuable programmer if you write clean programs with ample white space, frequent remarks, and straightforward code. Use parentheses in formulas if it makes the formulas clearer, and use variables for storing results in case you need the same answer later in the program. Break long calculations into several smaller ones.

Throughout the remainder of this book, you can read tips on writing maintainable programs. You and your colleagues will appreciate these tips when you incorporate them in your own C++ programs.

The Assignment Statement s

In C++, the assignment operator, =, behaves differently from what you might be used to in other languages. So far, you have used it to assign values to variables, which is consistent with its use in most other programming languages.

However, the assignment operator also can be used in other ways, such as multiple assignment statements and compound as- signments, as the following sections illustrate.

Multiple Assignment s

If two or more equal signs appear in an expression, each performs an assignment. This fact introduces a new aspect of the precedence order you should understand. Consider the following expression:

a=b=c=d=e=100;

This might at first seem confusing, especially if you know other computer languages. To C++, the equal sign always means: Assign the value on the right to the variable on the left. This right-to-left order is described in Appendix D’s precedence table. The third column in the table is labeled Associativity, which describes the direction of the operation. The assignment operator associates from the right, whereas some of the other C++ operators associate from the left.

C++’s Primary Mat h Operators - 图47Because the assignment associates from the right, the previous expression assigns 100 to the variable named e. This assignment produces a value, 100 , for the expression. In C++, all expressions produce values, typically the result of assignments. Therefore, 100 is assigned to the variable d. The value, 100 , is assigned to c, then to b, and finally to a. The old values of these variables are replaced by 100 after the statement finishes.

Because C++ does not automatically set variables to zero before you use them, you might want to do so before you use the variables with a single assignment statement. The following section of vari- able declarations and initializations is performed using multiple assignment statements.

mai n( )

{

i nt ct r , num_emp, num_dep;

f l oat sal es, sal ar y, amount;

ct r =num_emp=num_dep=0; sal es=sal ar y=amount =0;

/ / Rest of pr ogr am f oll ows.

In C++, you can include the assignment statement almost anywhere in a program, even in another calculation. For example, consider this statement:

val ue = 5 + (r = 9 - c) ;

which is a perfectly legal C++ statement. The assignment operator resides on the first level of the precedence table, and always pro- duces a value. Because its associativity is from the right, the r is assigned 9 - c because the equal sign on the extreme right is evaluated first. The subexpression (r = 9 - c ) produces a value (and places that value in r ), which is then added to 5 before storing the answer in val ue .

Example

C++’s Primary Mat h Operators - 图48Because C++ does not initialize variables to zero before you use them, you might want to include a multiple assignment operator to do so before using the variables. The following section of code ensures that all variables are initialized before the rest of the pro- gram uses them.

mai n( )

{

i nt num_emp, dependent s, age; f l oat sal ar y, hr _r at e, t axr at e;

/ / I ni t i ali ze all var i abl es t o zer o. num_emp=dependent s=age=hour s=0; sal ar y=hr _r at e=t axr at e=0. 0;

/ / Rest of pr ogr am f oll ows.

Compound Assignment s

Many times in programming, you might want to update the value of a variable. In other words, you have to take a variable’s current value, add or multiply that value by an expression, then reassign it to the original variable. The following assignment state- ment demonstrates this process:

sal ary=sal ary* 1. 2;

This expression multiplies the old value of sal ar y by 1.2 (in effect, raising the value in sal ar y by 20 percent), then reassigns it to sal ar y . C++ provides several operators, called compound operators, that you can use any time the same variable appears on both sides of the equal sign. The compound operators are shown in Table 8.4.

Table 8.4. C++’s compound operators.

Operator

Example

Equivalent

+=

bonus+=500;

bonus=bonus+500;

-=

budget -=50;

budget =budget - 50;

*=

sal ary*=1. 2;

sal ary=sal ary* 1. 2;

/ =

f act or / =. 50;

f act or =f act or / . 50;

%=

daynum%=7;

daynum=daynum%7;

C++’s Primary Mat h Operators - 图49The compound operators are low in the precedence table. They typically are evaluated last or near-last.

Examples

  1. C++’s Primary Mat h Operators - 图50You

    have been storing your factory’s production amount in a variable called pr od_amt , and your supervisor has just informed you that a new addition has to be applied to the

production value. You could code this update in a statement, as follows:

pr od_amt = pr od_amt + 2. 6; / / Add 2. 6 t o curr ent pr oduct i on.

Instead of using this formula, use C++’s compound addition operator by coding it like this:

pr od_amt += 2. 6; / / Add 2. 6 t o curr ent pr oduct i on.

  1. C++’s Primary Mat h Operators - 图51Suppose

    you are a high school teacher who wants to raise your students’ grades. You gave a test that was too difficult, and the grades were not what you expected. If you had stored each of the student’s grades in variables named

gr ade1 , gr ade2 , gr ade3 , and so on, you can update the grades in a program with the following section of compound assignments.

gr ade1*=1. 1; / / I ncr ease each st udent ’ s gr ade by 10. per cent .

grade2*=1. 1;

grade3*=1. 1;

C++’s Primary Mat h Operators - 图52/ / Rest of gr ade changes f oll ow.

  1. The precedence of the compound operators requires impor- tant

    consideration when you decide how to code compound assignments. Notice from Appendix D, “C++ Precedence Table,” that the compound operators are on level 19, much lower than the regular math operators. This means you must be careful how you interpret them.

For example, suppose you want to update the value of a

sal es variable with this formula:

4- f act or+bonus

You can update the sal es variable with the following statement:

sal es = * 4 - f act or + bonus;

This statement adds the quantity 4- f act or +bonus to sal es . Due to operator precedence, this statement is not the same as the following one:

sal es = sal es * 4 - f act or + bonus;

Because the *= operator is much lower in the precedence table than * or - , it is performed last, and with right-to-left associativity. Therefore, the following are equivalent, from a precedence viewpoint:

sal es *= 4 - f act or + bonus;

and

sal es = sal es * ( 4 - f act or + bonus) ;

Mixing Data Type s in Calculation s

You can mix data types in C++. Adding an integer and a floating-point value is mixing data types. C++ generally converts

C++ attempts to convert the smaller data type to the larger one in a mixed data-type expression.

the smaller of the two types into the other. For instance, if you add a double to an integer, C++ first converts the integer into a double value, then performs the calculation. This method produces the most accurate result possible. The automatic conversion of data types is only temporary; the converted value is back in its original data type as soon as the expression is finished.

If C++ converted two different data types to the smaller value’s type, the higher-precision value is truncated, or shortened, and accuracy is lost. For example, in the following short program, the floating-point value of sal es is added to an integer called bonus . Before C++ computes the answer, it converts bonus to floating-point, which results in a floating-point answer.

/ / Fil ename: C8DATA. CPP

/ / Demonst r at e mi xed dat a t ype i n an expr essi on. #i ncl ude <st di o. h>

mai n( )

{

i nt bonus=50;

C++’s Primary Mat h Operators - 图53f l oat sal ar y=1400. 50; f l oat t ot al ;

t ot al =sal ar y+bonus; / / bonus becomes f l oat i ng- poi nt

/ / but onl y t empor ar il y. pr i ntf (“ The t ot al i s %. 2f ” , t ot al ) ;

r et ur n 0;

}

Type Castin g

Most of the time, you don’t have to worry about C++’s auto- matic conversion of data types. However, problems can occur if you mix unsigned variables with variables of other data types. Due to differences in computer architecture, unsigned variables do not always convert to the larger data type. This can result in loss of accuracy, and even incorrect results.

You can override C++’s default conversions by specifying your own temporary type change. This process is called type casting. When you type cast, you temporarily change a variable’s data type

from its declared data type to a new one. There are two formats of the type cast. They are

( dat a t ype ) expr essi on

and

dat a t ype ( expr essi on )

C++’s Primary Mat h Operators - 图54where dat a t ype can be any valid C++ data type, such as i nt or f l oat , and the expr essi on can be a variable, literal, or an expression that combines both. The following code temporarily type casts the integer variable age into a double floating-point variable, so it can be multiplied by the double floating-point f act or . Both formats of the type cast are illustrated.

The variable age_f act or is assigned the value of the variable age (now treated like a double floating-point variable) multiplied by the variable f act or .

age_f act or = ( doubl e) age * f act or ; / / Tempor ar il y change age

/ / t o doubl e.

The second way of type casting adds the parentheses around the variable rather than the data type, as so:

age_f act or = doubl e( age) * f act or ; / / Tempor ar il y change age

/ / t o doubl e.

C++’s Primary Mat h Operators - 图55

Examples

  1. C++’s Primary Mat h Operators - 图56Suppose

    you want to verify the interest calculation used by your bank on a loan. The interest rate is 15.5 percent, stored as .155 in a floating-point variable. The amount of interest you owe is computed by multiplying the interest rate by the amount of the loan balance, then multiplying that by the number of days in the year since the loan originated. The following program finds the daily interest rate by dividing the annual interest rate by 365, the number of days in a year. C++ must convert the integer 365 to a floating-point literal automatically, because it is used in combination with a floating-point variable.

/ / Fil ename: C8I NT1. CPP

/ / Cal cul at e i nt er est on a l oan. #i ncl ude <st di o. h>

mai n( )

{

i nt days=45; / / Days si nce l oan or i gi nat i on.

C++’s Primary Mat h Operators - 图57f l oat pr i nci pl e = 3500. 00; / / Or i gi nal l oan amount

f l oat i nt er est _r at e=0. 155; / / Annual i nt er est r at e f l oat dail y_i nt er est ; / / Dail y i nt er est r at e

dail y_i nt er est =i nt er est _r at e/ 365; / / Comput e f l oat i ng-

/ / poi nt val ue.

/ / Because days i s i nt , i t t oo i s conver t ed t o f l oat. dail y_i nt er est = pr i nci pl e * dail y_i nt er est * days;

pr i nci pl e+=dail y_i nt er est;// Updat e pr i nci pl e wi t h i nt er est. pr i ntf (“ The bal ance you owe i s %. 2f\ n” , pr i nci pl e) ;

r et ur n 0;

}

The output of this program follows:

The bal ance you owe i s 3566. 88

  1. C++’s Primary Mat h Operators - 图58Instead

    of having C++ perform the conversion, you might want to type cast all mixed expressions to ensure they convert to your liking. Here is the same program as in the first example, except type casts are used to convert the integer literals to floating-points before they are used.

/ / Fil ename: C8I NT2. CPP

/ / Cal cul at e i nt er est on a l oan usi ng t ype cast i ng. #i ncl ude <st di o. h>

mai n( )

{

i nt days=45; / / Days si nce l oan or i gi nat i on.

f l oat pr i nci pl e = 3500. 00; / / Or i gi nal l oan amount f l oat i nt er est _r at e=0. 155; / / Annual i nt er est r at e f l oat dail y_i nt er est ; / / Dail y i nt er est r at e

dail y_i nt er est =i nt er est _r at e/f l oat ( 365) ; / / Type cast days

/ / t o f l oat.

/ / Because days i s i nt eger , conver t i t t o f l oat al so. dail y_i nt er est = pr i nci pl e * dail y_i nt er est * f l oat ( days) ;

pr i nci pl e+=dail y_i nt er est ; / / Updat e pr i nci pl e wi t h i nt er est. pr i ntf (“ The bal ance you owe i s %. 2f ” , pr i nci pl e) ;

r et ur n 0;

}

The output from this program is exactly the same as the previous one.

Review Question s

The answers to the review questions are in Appendix B.

  1. C++’s Primary Mat h Operators - 图59What

    is the result for each of the following expressions? a. 1 + 2 * 4 / 2

b. ( 1 + 2) * 4 / 2

c. 1 + 2 * ( 4 / 2)

  1. C++’s Primary Mat h Operators - 图60What

    is the result for each of the following expressions? a. 9 % 2 + 1

b. ( 1 + ( 10 - ( 2 + 2)))

  1. C++’s Primary Mat h Operators - 图61Convert

    each of the following formulas into its C++ assign- ment equivalents.

    1. a =

3 + 3

4 + 4

b. x = ( a - b) * ( a - c) 2

a2

  1. f =

b3

( 8 - x2) ( 4 * 2 - 1)

  1. d = -

( x - 9) x3

  1. C++’s Primary Mat h Operators - 图62Write

    a short program that prints the area of a circle, when its radius equals 4 and equals 3.14159. (Hint: The area of a circle is computed by * radius2.)

  2. Write the assignment and pr i ntf () statements that print the

    remainder of 100/ 3.

Review Exercise s

  1. C++’s Primary Mat h Operators - 图63Write

    a program that prints each of the first eight powers of 2 (21, 22, 23,...28). Please write comments and include your name at the top of the program. Print string literals that describe each answer printed. The first two lines of your output should look like this:

2 r ai sed t o t he f i r st power i s 2

2 r ai sed t o t he second power i s 4

  1. C++’s Primary Mat h Operators - 图64Change

    C8PAY.CPP so it computes and prints a bonus of 15 percent of the gross pay. Taxes are not to be taken out of the bonus. After printing the four variables, gr oss_pay , t ax_r at e , bonus , and gr oss_pay , print a check on-screen that looks like

a printed check. Add string literals so it prints the check- holder and put your name as the payer at the bottom of the check.

  1. C++’s Primary Mat h Operators - 图65Store

    the weights and ages of three people in variables. Print a table, with titles, of the weights and ages. At the bottom of the table, print the averages.

  2. Assume that a video store employee works 50 hours. He is paid $4.50

    for the first 40 hours, time-and-a-half (1.5 times the regular pay rate) for the first five hours over 40, and double-time pay for all hours over 45. Assuming a 28 per- cent tax rate, write a program that prints his gross pay, taxes, and net pay to the screen. Label each amount with appropri- ate titles (using string literals) and add appropriate com- ments in the program.

Summary

You now understand C++’s primary math operators and the importance of the precedence table. Parentheses group operations so they can override the default precedence levels. Unlike some other programming languages, every operator in C++ has a mean- ing, no matter where it appears in an expression. This fact enables you to use the assignment operator (the equal sign) in the middle of other expressions.

When you perform math with C++, you also must be aware of how C++ interprets data types, especially when you mix them in the same expression. Of course, you can temporarily type cast a variable or literal so you can override its default data type.

This chapter has introduced you to a part of the book concerned with C++ operators. The following two chapters (Chapter 9, “Rela- tional Operators,” and Chapter 10, “Logical Operators”) extend this introduction to include relational and logical operators. They enable you to compare data and compute accordingly.

C++’s Primary Mat h Operators - 图66C++’s Primary Mat h Operators - 图67