0

I'm using rand() in a loop to generate random numbers every time till the loop is complete, but it always gives the same number, what am I doing wrong?

 bool PlayGame(int Difficulty, bool bComplete)
{

    
    int CodeA =rand() % Difficulty + Difficulty;
    int CodeB =rand() % Difficulty + Difficulty;
    int CodeC =rand() % Difficulty + Difficulty;
   
  • 1
    You need to seed the random number generator 1 time at start of `int main()` – drescherjm Sep 05 '21 at 18:52
  • you need to seed the random generator : Also see : https://stackoverflow.com/questions/69056209/c-random-number-same-sequence-every-time/69056326?noredirect=1#comment122052380_69056326. For C++ consider using functions from the header file (rand is less random and more "c" then "c++") – Pepijn Kramer Sep 05 '21 at 18:55
  • Just curious: there's been a flurry of questions similar to this in the past few days. Is there a course somewhere that's prompting people to write code that uses random numbers? – Pete Becker Sep 05 '21 at 18:57
  • @PeteBecker Yes random numbers and c-style arrays ;) – Pepijn Kramer Sep 05 '21 at 18:59
  • Thanks for the help everyone! I'm really new haha – EmberMan Sep 05 '21 at 19:04

2 Answers2

2

You can use current time as seed for random generator by setting srand(time(0)); at start

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
// Driver program
int main(void)
{
    // This program will create different sequence of
    // random numbers on every program run
 
    // Use current time as seed for random generator
    srand(time(0));
 
    for(int i = 0; i<4; i++)
        printf(" %d ", rand());
 
    return 0;
}


Output 1:
453 1432 325 89

Output 2:
8976 21234 45 8975

Output n:
563 9873 12321 24132

Ref.

Mayur
  • 2,583
  • 16
  • 28
2

If random numbers are generated with rand() without first calling srand(), your program will create the same sequence of numbers each time it runs.

The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1)

so, set srand(time(0)); at start of the program

Prithvi Raj
  • 1,611
  • 1
  • 14
  • 33
  • 1
    And, in case it isn't clear, generating the same sequence every time is a good thing. It's important for debugging, and, more generally, for understanding what your program is doing. Once it's working right, add a seed so that you get varied behavior. – Pete Becker Sep 05 '21 at 21:07