Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C For Dummies 2nd Ed 2004.pdf
Скачиваний:
43
Добавлен:
17.08.2013
Размер:
8.34 Mб
Скачать

Chapter 11: C More Math and the Sacred Order of Precedence 141

Amazing how easy the computer could figure that out! Of course, at this point in the game, you can easily afford the $705 in funny money. All you need is for some poor sap to land on St. Charles Place with its hotel, and you make the money back jiffy-pronto.

Notice how the temp variable is used to hold and help convert two dif­ ferent strings into numbers? This example illustrates how variables can change and, well, be variable.

The mathematical computation in Line 17 works because of something called the Sacred Order of Precedence, which is covered in the very next section.

You may think, and rightly so, that the total displayed by the program

should be a float variable. After all, dollar amounts usually have a deci­ mal part: $705.00 rather than $705. But, in this case, because all the values are integers, it just makes more sense to stick with a total inte­ ger variable. Keep in mind that integers are faster, which is especially apparent in larger programs.

The Sacred Order of Precedence

Precedence refers to what comes first. The fact that the theater is on fire, for example, takes precedence over the fact that you’ll miss the second act if you leave in a hurry.

The order of precedence is a double redundancy (which in itself is redundant several times over). It refers to which of the mathematical operators has prior­ ity over the others. For example, a plus sign just can’t march into the middle of a group of numbers and expect to add things the way it wants to. In C, other mathematical operations are done before addition. It’s just proper.

A problem from the pages of the dentistry final exam

Witness with your own eyes the following long and complex mathematical equation that may one day slink into one of your C programs:

answer = 100 + 5 * 2 - 60 / 3;

This question is one of those tough math questions from the dentistry final exam. Yes, most dentists would rather be pulling teeth — even their own. The preceding problem isn’t really a problem for you, though. The computer fig­ ures the answer. But what is it?

142 Part III: Giving Your Programs the Ability to Run Amok

Is the answer 50? One hundred plus 5 is 105; times 2 is 210; minus 60 is 150; divided by 3 is 50. Does the compiler force the computer to do that for you automatically? Or should the value 90 be placed into the answer variable?

Ninety? Yes, the value of the answer variable is 90. This all has to do with My Dear Aunt Sally and the order of precedence. Before getting into that, I show you the following program, DENTIST.C, which you can type to prove that the answer is 90 and not 50:

#include <stdio.h>

int main()

{

printf(“%d”,100+5*2-60/3); return(0);

}

Enter this short and sweet program into your editor. Compile it. Run it. It’s a printf() statement, with only %d in double quotes. That’s followed by a comma and then the math question from the dentistry final.

Run the program. The result should shock you:

90

The order of your mathematical equations is important. Not knowing how the C compiler works out its math means that you may not get the answer you want. That’s why you have to know the order of precedence and, more importantly, My Dear Aunt Sally.

When the DENTIST.C program runs, the computer works on the equation 100+5*2-60/3 first in the printf() function. The result is then passed over to the fill-in-the-blanks %d and is displayed on the screen.

I could have expanded DENTIST.C to declare the answer integer vari­

able, assign the value to that variable, and then use printf() to display the variable’s contents. But, naaah. That would be too long of a program. The C language is full of short ways to do things. The printf() state­ ment in DENTIST.C is just one example of a scrunched-up C program.

What’s up, Sally?

My Dear Aunt Sally is a mnemonic device, or “a silly thing we say to remem­ ber something we would forget otherwise, which isn’t saying much because we nearly always forget our own phone number and family birthdays.” In this case, My Dear Aunt Sally is a mnemonic for

Chapter 11: C More Math and the Sacred Order of Precedence 143

Multiplication

Division

Addition

Subtraction

MDAS is the order in which math is done in a long C language mathematical equation — the order of precedence.

The compiler scopes out an entire equation — the whole line — and does the multiplication first and then the division and then the addition and subtrac­ tion. Things just aren’t from left to right any more. Figure 11-1 illustrates how the mathematical example in the preceding section figures out to be 90.

Figure 11-1:

How the C compiler figures out a long math function.

answer = 100 + 5 *

2 - 60 /

3;

answer = 100

+

10

- 60 /

3;

answer = 100

+

10

-

20;

answer =

110

 

-

20;

answer =

 

 

90;

 

 

 

 

 

 

 

 

Here’s another puzzle:

answer = 10 + 20 * 30 / 40;

In this statement, the multiplication happens first and then the division and then the addition. When the multiplication and division are next to each other, as in the preceding line, it goes from left to right.

When the computer is finished counting its thumbs and the preceding state­ ment is resolved, the answer variable contains the value 25. You can prove it by editing the DENTIST.C program and replacing the math that’s already there, in the preceding math equation. Recompile and run the program to confirm that the answer is 25. Or, just trust me and let it go at that.

144 Part III: Giving Your Programs the Ability to Run Amok

My Dear Aunt Sally. Multiplication (*), division (/), addition (+), and sub­ traction (–) are done in that order in the C language’s long mathematical equations.

The reason that the order of precedence is important is that you must organize your mathematical equations if you expect the proper answer to appear.

The ASSESSED.C program, from the preceding section, also takes advan­ tage of the order of precedence:

total=houses*40+hotels*115;

The number of houses times 40 is worked out first, and then hotels times 115 is done second. The last step is to add the two.

A way to control the order of precedence is by using parentheses, as dis­ cussed in the obviously named section “Using parentheses to mess up the order of precedence,” later in this chapter.

The confounding magic-pellets problem

I hated those math-class story problems when I was a kid. In fact, I still do. In any event, here I am, in my adulthood, making up something like the following:

Suppose that you have 100 of these magic pellets. They double in quantity every 24 hours. After a day, you have 200. But, first you have to give 25 to the butcher in exchange for three dozen lamb’s eyeballs for a casserole you want to surprise your spouse with. If so, how many magic pellets would you have the next day?

Don’t bother stewing over the problem. The equation is

100 - 25 * 2;

That’s 100 magic pellets minus 25 for the eyeballs and then times 2 (doubled) the next day. In your head, you can figure that 100 minus 25 is 75. Multiply 75 by 2 and you have 150 magic pellets the next day. But in C, this just wouldn’t work; the order of precedence (that Sally person) would multiply 25 by 2 first. That would calculate to 50 magic pellets the next day. What a gyp!

The following C program, PELLETS.C, illustrates how the magic-pellet prob­ lem is confounded by C’s order of precedence. This program is a somewhat more complex version of the basic DENTIST.C program, presented earlier in this chapter: