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

Chapter 25

Math Madness!

In This Chapter

Using more complex math functions

Understanding the pow() and sqrt() functions

Linking in the math library for Unix

Doing the post-/pre-increment/-decrement thing

Most people think that computer programming is all math. Boy, are they wrong. It involves math, to be sure, but the hard part — figuring out

the answer — is done by the computer. So, what’s the beef? Why run scream­ ing and hiding from this innocent, kind little chapter that merely discusses the various C language details, spells, and dance steps for juggling numbers?

More on Math

The basic four computer math symbols should be familiar to you by now:

Addition symbol: +

Subtraction symbol: –

Multiplication symbol: *

Division symbol: /

These doojabbies are common throughout computerdom. If you use a spread­ sheet, they’re the symbols you use to do math. All these symbols are clus­ tered about your keyboard’s numeric keypad. The most cryptic one is the asterisk (*), for multiplication.

Other than the symbols, the only thing worth keeping in mind about math in C is that the calculation always goes on the right side of the equal sign. Therefore:

meals=breakfast+lunch+dinner;

314 Part IV: C Level

This equation, assuming that everything is a numeric variable, is correct. The following statement, however, is a boo-boo:

breakfast+lunch+dinner=meals;

The math goes on the right side of the equal sign. Always.

Goofing up a math equation is where you get those horrid Lvalue errors.

You can always remember the cryptic mathematical symbols in the C language by looking at your keyboard’s numeric keypad; each of the symbols is right there.

Math problems in C work from left to right, the way you read. Some operations, however, have priority over others. If you forget, remember My Dear Aunt Sally, from Chapter 11.

Another mathematical symbol is the %, which means modulus. This dreadful topic is covered in Chapter 26, where it’s appropriate uses are apparent.

It can be said that a C language operator exists for every odd symbol, shape, jot, and tittle on your keyboard. This statement is almost true. Pray that you never have to memorize them all.

Taking your math problems to a higher power

Two mathematical operations that seem to be lacking in C’s granola of symbols are the power-of symbol and the square root symbol. Of course, I’m assuming that you give a hoot about either of them, but you never know when they may crop up.

The power-of thing deals with problems that contain the words squared and cubed in addition to power of. For example:

“Four squared” means 4 × 4, or 42. The latter reads “Four to the second power.”

“Four cubed” means 4 × 4 × 4, or 43. This one reads “Four to the third power.”

Beyond cubed, or to the third power, you just say the power number; So, 4 × 4 × 4 × 4 × 4 is 45, or “four to the fifth power.” (Don’t even bother trying to figure out the answer; the computer does it for you!)

Chapter 25: Math Madness! 315

Alas, there just isn’t any handy way to express 45 in C. There’s no cool symbol. For example, you cannot write

answer=4♠5;

This line just doesn’t work, even considering that isn’t a symbol anywhere on the keyboard (even in Las Vegas). It would be nice, but it just isn’t so.

You need to draw on the C language’s vast library of supplemental math func­ tions. A few dozen functions compute such things as power-of, square root, terrifying trigonometric functions, and so on (see Table 25-1, later in this chapter). To take a number to a higher power, you use the pow() function.

The pow() function is used to calculate one value taken to a certain power, such as 4 taken to the second power (42). Here’s the format:

value = pow(n,p)

In this line, value, n, and p all must be double-precision variables (defined using the double declaration). The pow() function calculates n to the p power. The answer is stored in the value variable.

To prevent your compiler from going mad, you must include the MATH.H header file at the beginning of your source code. Stick the following line up there somewhere:

#include <math.h>

This line is required for the pow function as well as for other math functions you may dare to use.

Putting pow() into use

Using the pow() function is easy — it’s just like using any other function. Just declare your variables as doubles, include the MATH.H thing, and you’re all set. Why not put it forth in one of those endearing math-sentence problems? To wit:

Suppose that you have tasked Milton — your brilliant, Mensa-club-leader son — with decorating the house for Christmas. Because he’s too smart to drive,

he directs you to go to the store and pick up 28 (“two to the eighth power”) twinkly lights. You quickly dash off to your computer and use the C language to decipher what he means:

316 Part IV: C Level

#include <stdio.h> #include <math.h>

int main()

{

double lights;

 

lights=pow(2,8);

/* figure 2 to the 8th power */

printf(“Milton, we need %0.f lights.\n”,lights); return(0);

}

Type this silly program on a new screen in your editor. Save the contraption to disk as LIGHTS1.C.

Compile and run.

If you get a linker error in your Unix-like operating system, please refer to the following sidebar, “Gotta link in that math library!”

Here’s the output:

Milton, we need 256 lights.

There. Now you both know how many lights are needed. The computer suc­ cessfully concluded that 28 is equal to 256.

Two to the eighth power is written out longways; thus:

2 x 2 x 2 x 2 x 2 x 2 x 2 x 2

The pow function expects to deal with double variables. In fact, many of the MATH.H functions deal with anything except integers.

Constant values, such as 2 and 8 inside LIGHTS1.C, don’t have to be doubles (or even typecast as doubles). Thankfully, the compiler is pretty smart about that stuff.

The printf() placeholder used for printing a floating-point number is %f. It works for both floats and doubles. The 0. part of %0.f tells printf() to format the floating-point output using only the part of the number on the left of the decimal.

Some languages and spreadsheets use the caret symbol (^) for power, as in 2^8 for 28. This technique doesn’t work in C. (The ^ in C is a bitwise exclusive OR logical operation, whatever that means.)