don't get random numbers every time

This is my program i have to choose for random number between 1-25 and display them the program works perfectly just that every time i run its always the same numbers. I still haven't learned about crime so I'm trying to avoid since the professor said to use only what we know. I saw in the book that they used stand(99) but it doesn't work in my case. Any help is appreciated thank you.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <cstdlib> // include library to use rand

using namespace std;

int main(){
    int winner1;        // declare variables
    int winner2;
    int winner3;
    int winner4;
    bool same= true;

    
    
    while(same==true){   // while statement that will run if at least two random numbers are the same
        srand(99);
     winner1= rand() % 26;
     winner2= rand() % 26;
     winner3= rand() % 26;
     winner4= rand() % 26;
        
        
        if( winner1==winner2 || winner1==winner3 || winner1==winner4 || winner2==winner3 || winner2==winner4 || winner3==winner4)
            same=true;
        else                    // will exit loop when all four random numbers are different
            same=false;
    }
    
    cout << "The winning numbers are: " << winner1 <<", " << winner2 << ", " << winner3 << ", " << winner4 <<endl;
    // display the winning numbers
    return 0;
}
When you seed srand, the sudorandom number generator will give a specific sequence of numbers based on that seed.

1) Seed the numbers only once. Do that at the start of main(). This way, winner1-4 will be different for each iteration of the while loop (currently they are always the same).

2) Seed with something like srand( time(NULL) );. This will seed the random number generator with a different number each time (because it's never the same value twice unless you're calling it in the same second).
Last edited on
unless you're calling it in the same second
Well time returns the number of milliseconds from midnight...

Also as mentioned rand is a pseudo random number generator which means its actually a sequence of numbers based off the starting seed the formula will look something along the lines to:
1
2
x0 = seed, P1 = some_intial_value , P2 = some_inital_value,
xn+1 = (P1 * xn + P2) % n
Last edited on
@giblit
The value returned generally represents the number of seconds since 00:00 hours, Jan 1, 1970 UTC (i.e., the current unix timestamp)


http://www.cplusplus.com/reference/ctime/time/
Last edited on
Topic archived. No new replies allowed.