reset password
Author Message
yash3ahuja
Posts: 5
Posted 02:12 Jan 09, 2014 |

Hello everyone,

I just thought I would point out that if you forget to seed random in your labs you may run into trouble while testing your programs (as you're going to think your program is bugged since it will give the same output every time you run it).

To seed rand, include time.h ("#include <time.h>") and then add "srand(time(NULL))" somewhere in main before you call rand.

Hopefully you guys won't have to waste any time like I did,

Yash

kknaur
Posts: 540
Posted 10:37 Jan 09, 2014 |

This is a good post.  I forgot to mention this in class when using the rand() function.  The rand() function generates its numbers based on a formula.  This formula has a starting point which we call the "seed".  When you use rand() by itself without supplying a seed to the function, I believe the default seed that is used is 1.  So if you use the same seed every time, the same sequence of random numbers will be generated every time.  In order to generate different numbers every time you run your program you can supply the current system time as the seed by using the time() function found in the "time.h" or "ctime" libraries, just like Yash has already mentioned.

Here is a code example using this method.

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main() {

    /*Seed the rand() function by calling srand() and giving it the current
      system time as an argument.  NOTE: you only need to call it one time
      before you call rand()*/
    srand(time(NULL));

    for (int i = 0 ; i < 10 ; i++) {
        cout << rand() % 11 << endl;
    }

    return 0;
}

For problem 3 if you didn't supply a seed and you get the same output every time then that is ok with me.  Otherwise if you would like to have different output every time you run the program you may follow the above method.