-3

I didn't understand what everyone said here: srand(time(NULL)) doesn't change seed value quick enough and I am supposed to use the srand() to generate a different random number every time but I keep getting the same number, any suggestions?

#include <iostream>
 #include <time.h>
using namespace std;

int main()
{
    int n, num;
    cout<<"Enter the number:\n";
    cout<<"n= "<<n<<endl;
    cin>>num;
     srand(time(NULL));
    n= rand()%10+1;

    if(n==num)
        cout<<"win\n";
    else
        cout<<"lose\n";


    return 0;
}
Community
  • 1
  • 1
Amal
  • 37
  • 1
  • 5

2 Answers2

2
cout<<"n= "<<n<<endl;

Here are you printing n before initialization that exhibits undefined behavior.

Solution
Print it after n= rand()%10+1;

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
0

srand(int) shakes numbers depends on the value passed by the argument. If you give the same number, the random numbers will be the same. In your URL, people call srand(time(NULL)) twice but the clock of the computer did not had the time to change between the two calls. So the random numbers are the same.