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?

Recommended Answers

All 4 Replies

>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.

>(Visual C++, I'm Guessing)

Nope, DEV_C++ :)

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.

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

Be a part of the DaniWeb community

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