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

(Romina) #1

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


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


As always, the best way to understand these types of functions is to see an example. The following
code uses the rand() function to roll two dice and present the result. Then the user gets to decide
whether a second roll of the dice is going to be higher, lower, or the same as the previous roll:


Click here to view code image


// Example program #2 from Chapter 20 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter19ex2.c
/* This program rolls two dice and presents the total. It then asks
the user to guess if the next total will be higher, lower, or equal.
It then rolls two more dice and tells the user how they did. */
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

main()
{
int dice1, dice2;
int total1, total2;
time_t t;
char ans;
// Remember that this is needed to make sure each random number
// generated is different
srand(time(&t));

// This would give you a number between 0 and 5, so the + 1
// makes it 1 to 6
dice1 = (rand() % 5) + 1;
dice2 = (rand() % 5) + 1;
total1 = dice1 + dice2;
printf("First roll of the dice was %d and %d, ", dice1, dice2);
printf("for a total of %d.\n\n\n", total1);
do {
puts("Do you think the next roll will be ");
puts("(H)igher, (L)ower, or (S)ame?\n");
puts("Enter H, L, or S to reflect your guess.");
scanf(" %c", &ans);
ans = toupper(ans);
} while ((ans != 'H') && (ans != 'L') && (ans != 'S'));
Free download pdf