20. Can C Do My Math Homework?

The Built-In Numeric Functions Show You

image

This chapter extends your knowledge of built-in functions to the numeric functions. C helps you do math that the C operators can’t do alone. More than anything else, the C built-in numeric functions supply routines that you don’t have to write yourself.

A lot of C’s built-in math functions are highly technical. Not that their uses are difficult, but their purposes might be. Unless you need trigonometric and advanced math functions, you might not find a use for many of the functions described in this chapter.

Clue

image

Some people program in C for years and never need many of these functions. You should read this chapter’s material to get an idea of what C can accomplish so you’ll know what’s available if you ever do need these powerful functions.

Practicing Your Math

All the functions this chapter describes require the use of the MATH.H header file. Be sure to include MATH.H along with STDIO.H if you use a math function. The first few math functions are not so much math functions as they are numeric functions. These functions convert numbers to and from other numbers.

The floor() and ceil() functions are called the floor and ceiling functions, respectively. They “push down” and “push up” non-integers to their next lower or next higher integer values. For example, if you wanted to compute how many dollar bills are in a certain amount of change (that includes dollars and cents), you could use floor() on the amount. The following code does just that:

image

Warning

image

Although ceil() and floor() convert their arguments to integers, each function returns a float value! That’s why the dollars variable was printed using the %f conversion code.

The ceil() function (which is the opposite of floor()) finds the next highest integer. Both ceil() and floor() work with negative values too, as the following few lines show:

image

Note

image

The negative values make sense when you think about the direction of negative numbers. The next integer down from -18.5 is -19. The next integer up from -18.5 is -18.

See, these functions aren’t so bad, and they come in handy when you need them.

Doing More Conversions

Two other numeric functions convert numbers to other values. The fabs() function returns the floating-point absolute value. When you first hear about absolute value, it sounds like something you’ll never need. The absolute value of a number, whether it is negative or positive, is the positive version of the number. Both of these printf() functions print 25:

printf("Absolute value of 25.0 is %.0f. ", fabs(25.0));
printf("Absolute value of -25.0 is %.0f. ", fabs(-25.0));

Note

image

The floating-point answers print without decimal places because of the .0 inside the %f conversion codes.

Clue

image

Absolute values are useful for computing differences in ages, weights, and distances. For example, the difference between two people’s ages is always a positive number, no matter how you subtract one from the other.

Two additional mathematical functions might come in handy, even if you don’t do heavy scientific and math programming. The pow() function raises a value to a power, and the sqrt() function returns the square root of a value.

Clue

image

You can’t compute the square root of a negative number. The fabs() function can help ensure that you don’t try to take the square root of a negative number by converting the number to a positive value before you compute the square root.

The following code prints the value of 10 raised to the third power and the square root of 64:

image

Here is the output of these printf() functions:

10 raised to the 3rd power is 1000.
The square root of 64 is 8.

Getting Into Trig and Other Really Hard Stuff

Only a handful of readers will need the trigonometric and logarithmic functions. If you know you won’t, or if you hope you won’t, go ahead and skip to the next section. Those of you who need them now won’t require much explanation, so not much is given.

The primary trigonometric functions are explained in Table 20.1. They each require an argument expressed in radians.

Table 20.1. C’s trigonometric functions.

image

The primary log functions are shown in Table 20.2.

Table 20.2. C’s logarithmic functions.

image

The following program prints the results of the six trig and log functions:

image

Here is the output. Does C compute these values faster than you can with pencil and paper?

image

Getting Random

For games and simulation programs, you often need to generate random values. C’s built-in rand() function does just that. It returns a random number from 0 to 32767. The rand() function requires the STDLIB.H (standard library) header file. If you want to narrow the random numbers, you can use % (the modulus operator) to do so. The following expression puts a random number from 1 to 6 in the variable dice:

dice = (rand() % 5) + 1;  /* From 1 to 6 */

Warning

image

Because a die can have a value from 1 to 6, the modulus operator returns the integer division remainder (0 through 5), and then a 1 is added to produce a die value.

There’s one crazy thing you must do if you want a truly random value. It is described next.

Note

image

You might always want a different set of random numbers produced each time a program runs. Games need such randomness. However, many simulations and scientific studies need to repeat the same set of random numbers. rand() will always do that if you don’t seed the random-number generator.

To seed the random-number generator means to give it an initial base value from which the rand() function can offset with a random number. Use srand() to seed the random-number generator. The number inside srand()’s parentheses must be different every time you run the program unless you want to produce the same set of random values.

The trick to giving srand() a different number each run is to put the exact time of day inside srand()’s parentheses. Your computer keeps track of the time of day down to hundredths of a second.

Because there’s no time to go into much detail, let’s cut to the chase and see how most C programmers produce truly random values. The following code is similar to a section from the Blackjack game in Appendix B. The comments explain things that need clarifying at this point.

image

Clue

image

You must include TIME.H before seeding the random-number generator with the time of day, as done here.

Note

image

The bottom line is this: If you add the two weird-looking time statements shown here, rand() will always be random and will produce different results every time you run a program.

Rewards

image

• Use the built-in numeric functions when you can so that you won’t have to write code to perform the same calculations.

• Lots of the numeric functions such as floor(), ceil(), and fabs() convert one number to another.

Be sure to seed the random-number generator with the time of day if you want random numbers with rand() to be different every time you run a program.

Pitfalls

image

• Don’t feel that you must master the trig and log functions if you don’t need them now. Many C programmers never use them.

• Don’t use an integer variable to hold the return value from this chapter’s math functions (unless you typecast the function return values) because they return floats or doubles even though some, like ceil(), produce whole-number results.

In Review

The goal of this chapter was to explain lots of built-in math functions that can make numeric data processing easier. C contains a rich assortment of integer functions, numeric conversion functions, time and date functions, and random-number generating functions.

You don’t have to understand every function in this chapter at this time. You might write hundreds of C programs and never use many of these functions. Nevertheless, they are in C if you need them.

Code Example

image

Code Analysis

These code lines give quick examples of how you would use some of the math functions described in this chapter. The program contains four pairs of statements. Each pair contains a function call and the output of that function call’s resulting value.

Notice that rand() is the only function in the code that doesn’t accept an argument. If the rand() function based its answer on a value you passed, rand() wouldn’t be very random.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset