0

Hey,
I was just mucking around when using rand() and noticed every time it comes out as a output of 41?

#include <iostream>

using namespace std;

int main()
{
    unsigned int randomNumber;
    unsigned int guess;
    unsigned int guesses;
    
    randomNumber = rand(); 
    cout << randomNumber << endl;
    
    system("PAUSE > nul");
}

Should i use srand() or something?

3
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by Narue
0

>Should i use srand() or something?
You answered your own question. Yes, you should use srand if you want the sequence to start with a different number each time. Otherwise it always gets seeded to 1, and on your compiler (Visual C++, I'm guessing) the first number generated with a seed of 1 is 41.

0

Yes, you should use srand if you want the sequence to start with a different number each time.

Of course Narue is right, but with one remark:
Only if you seed srand() with a different number each time, else you'll still get the same number sequence every time you run your program.

A common practice is to seed srand() with time(NULL): srand(time(NULL)); . This will give you a pseudorandom number which will be good enough for 99,999% of the programs. Time is declared in time.h.

0

>Nope, DEV_C++
Same diff. They both (Visual C++ and MinGW) use the implementation from msvcrt.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.