#include <Stdafx.h>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;

int rand_0toN1(int n);

int main()
    int n, i;
    int r;

    srand(time(NULL));      // set a seed for random-number generation.

    cout<< "Enter number of dice to roll: ";
    cin>> n;

    for(i = 1; i <= n; i++)
        r = rand_0toN1(6) + 1;

        cout<< r << " ";
    return 0;

// random 0 to n1 function
int rand_0toN1(int n)
    return rand() % n;

I'M having trouble understanding a few lines of this program, the first one is srand(time(NULL));
I'M assuming srand is the function so what is time in this code. Also, if this line is generating a random number where is it storing the number, I don't see a variable anywhere.
And the line r = rand_0toN1(6) + 1, what's the + 1 all about? Thanks.

Recommended Answers

All 5 Replies

srand doesn't generate a random number, it sets the seed for the random number generator. The time part is using the current time when the program is run as the seed. This effectively means that the seed is different for each run and the program will do different things each time it's run.

rand_0toN is a function that wraps rand - the function that generates the actual random number. It limits the maximum value that the random number can take to be less than N (6 in this case). The random number is stored in r on line 22 and is printed out on line 24.

Yup... agree with him.. When u use srand, irrespective of when u run the program and when it isnt initialised with a random variable at any time, it will always generate the same set of random numbers... Run it at 4:00 Am, it'll probably generate 4,7,8,3,2.. Run it at 4:01 am, the same thing.. in the same sequence.. At 5:00 pm 4 days later.. the same thing... Not so random are they then ?

So is srand a function? Is the time thats inside the srand() also another function or some type of built in C++ variable? Thanks guys.

Yes, it's a function. It returns a value of type time_t, which is often just a typedef'd int. You can read more about it here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.