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

Chapter 26

The Old Random-Number Function

In This Chapter

Introducing the rand() function

Seeding the rand() function

Performing mod (%) calculations

Producing random numbers in a given range

The original plans for this book had it run about 1,600 pages. That’s because I never wanted to break the slow, easy pace with which the C language was taught. The problem is that you cannot fit 1,600 pages into a roughly 400-page

book without cutting something out. What to cut out?

You may think that it’s odd that I chose to cut what I did, yet kept this chapter on the random-number function. I did that because, believe it or not, random numbers are a big deal when it comes to programming a computer. They come in handy, for example, with computer games. No computer game would ever be possible without a random number here or there. Without them, the game would be predictable: “Oh, I’m passing by the planet Bothar again, and here is where the Omnivorous Space Slug tries to taunt me into a gavotte.”

On Being Random

What’s random? The next card drawn from a well-shuffled deck. The roll of a dice. The spin of a roulette wheel. Whether Cindy will overlook your huge beer gut as you attempt your first date after the divorce. These are all random, maybe-this-or-that events. If you want to include this random aspect in your programs, you need a special function that produces random numbers. After that’s done, no one can predict when the Enterprise will be attacked or when the tornado will whip through your village or whether Door Number 2 leads to the treasure this time or to certain peril.

326 Part IV: C Level

The phone company is rumored to have a random-number program that it routinely uses to foul up your bill.

Random-number routines are the root of the most evil program ever devised for a budding programmer: The Guess the Number program. I spare you that torture in this book. (Well, maybe not.)

In the C language, random numbers are produced by using the rand() function. I formally introduce it next.

Random numbers must be seeded in order for them to be more unpre­ dictable. I cover this subject also, later in this chapter.

Random numbers generated by a computer aren’t truly random. See the nearby sidebar, “You too can waste a few seconds reading this informa­ tion about random numbers,” for more information.

Using the rand() function

Random numbers are generated in C by using the rand() function. It spits back a random number depending on the whims of your PC’s microprocessor carefully combined with the birthdate of the guy who wrote your C compiler plus his girlfriend’s weight in drams. Or something like that.

Here’s the format for the rand() function:

int rand();

You too can waste a few seconds reading this information about random numbers

Are they random numbers? Only if they can’t be predicted. Unfortunately, with computers, the numbers can be predicted. They’re still more or less jumbled, like street numbers in Seattle. But, overall, the random numbers a computer gen­ erates aren’t truly random. Instead, they’re pseudorandom.

A pseudo- (“SOO-doh”) random number is random enough for most purposes. But because

the number is based on a computer algorithm, or set routine, its outcome isn’t truly random. Even if you base the random number on the time of day — or seed the random number by using another, potentially random value — the results still aren’t random enough to appease the math­ ematical purists. So you live with it.

Chapter 26: The Old Random-Number Function 327

The rand() function returns an integer value, somewhere in the range of 0 through 32,767. If you want to save the random number into the r variable, you use the following statement:

r=rand();

Cinchy stuff.

To make the compiler understand the rand() function, you must add this line at the beginning of your source code:

#include <stdlib.h>

This line tells the compiler all about the rand() function and makes every­ one happy.

The following program shows the rand() function in action. RANDOM1.C produces 100 random numbers, which it displays neatly on the screen. The random numbers are produced by the rand function inside this program’s rnd() function. The reason that this was done, as you may be fearing, is that you modify the rnd() function to new levels of spiffiness as this chap­ ter progresses.

#include <stdio.h> #include <stdlib.h>

int rnd(void);

int main()

{

int x;

puts(“Behold! 100 Random Numbers!”); for(x=0;x<100;x++)

printf(“%d\t”,rnd());

return(0);

}

int rnd(void)

{

int r;

r=rand();

return(r);

}

Type the source code for RANDOM1.C into your editor. Double-check every­ thing. Save the file to disk as RANDOM1.C.

328 Part IV: C Level

Compile the program. Fix any errors, which are probably limited to missing semicolons or forgotten parentheses.

Run it!

The output displays ten columns by ten rows of random numbers on the typi­ cal console display — no point in repeating that here! But, on your screen, note how the numbers are different — nay, random. I mean, would you have thought of that many that quickly?

The random numbers are probably in the range of 0 to 32,000something — as promised. The numbers you see on your screen are probably different from those from the code just shown.

Some versions of the GCC compiler produce larger random number values than 0 to 32,000-something. That maximum value is set by the value of RAND_MAX, as defined in the SDTLIB.H header. On my FreeBSD machine, for example, the value of RAND_MAX is 0x7FFFFFF (hexadeci­ mal), which translates to 2,147,483,647.

To see the value of RAND_MAX on your computer, add this line to the pro­ gram before the return(0); in the main() function:

printf(“\nRAND_MAX is equal to %u\n”,RAND_MAX);

%u is the placeholder for an unsigned long integer.

Planting a random-number seed

Ho! Before you get all happy about the new CASINO program you’re about to write and sell for millions to Las Vegas, try rerunning the RANDOM1.C program again. Just choose Run from your compiler’s integrated environ­ ment or type the RANDOM1 command again at the DOS prompt:

(Output suppressed!)

Yup, on your screen, you see 100 more random numbers. Wait a second. Aren’t those the same numbers? Identically the same numbers? Did the compiler goof? Did you foul up?

Fortunately, that was no error. The computer generated the set of random numbers because that’s all it knows. Sure, they’re random, all right, but they’re the same numbers because, between then and now, the compiler’s rand() function remained unchanged.

Don’t feel cheated! This situation is a common one. The rand() function is only quasirandom. To make it more random (more pseudorandom), you have to plant a wee, tiny seed. This seed is a value the compiler uses to help make