C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
The sine of a 90-degree angle is 1.000
The tangent of a 75-degree angle is 3.732
The arc cosine of a 45-degree angle is 0.667
The arc sine of a 30-degree angle is 0.551
The arc tangent of a 15-degree angle is 0.256
Section 4: Log functions
e raised to 2 is 7.389
The natural log of 5 is 1.609
The base-10 log of 5 is 0.699

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:


Click here to view code image


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

Note

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.

You must do one crazy thing if you want a truly random value.


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 the srand() 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 the
srand() parentheses. Your computer keeps track of the time of day, down to hundredths of a
second. So first declare a time variable, using the time_t declaration, and then send its address
(using the & character at the front of the variable name) to the srand() function.


Note

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.
Free download pdf