1

In next code I've same result everytime although using "srand" and followed instructions of the next link rand() and srand() in C/C++:

#include <iostream>
#include <cstdlib>

using namespace std;

int main(void)
{

int i, x;


srand(5);

for(i=1;i<=10;++i)
{

x=rand()%5;
cout << x << endl;

}
return 0;
}
pascal111
  • 37
  • 3

2 Answers2

1

The reason you are getting the same result is that you are always passing the same value (5) to srand.

As the linked page notes, srand(time(0)) is a common way to get the seed to vary.

m90
  • 233
  • 1
  • 6
0

For using it in a fast Loop you have to code it different.
I make an example for you that produce different random numbers from your posted...
https://www.geeksforgeeks.org/rand-and-srand-in-ccpp/
...and @Martin York' Example from here...
Recommended way to initialize srand?

rnd.c

// C program to generate random numbers
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
// Driver program
int main(void)
{
    struct timeval time; 
    // gettimeofday(&time,NULL);
    // microsecond has 1 000 000
    // Assuming you did not need quite that accuracy
    // Also do not assume the system clock has that accuracy.
    // The trouble here is that the seed will repeat every
    // 24 days or so.
    // If you use 100 (rather than 1000) the seed repeats every 248 days.
    // Do not make the MISTAKE of using just the tv_usec
    // This will mean your seed repeats every second.
    srand((time.tv_sec * 1000) + (time.tv_usec / 1000)); 

    for(int i = 0; i<4; i++)
        printf("%d\n", rand());

    return 0;
}

And run after compiling it: for i in {1 2 3 4 5}; do ./rnd; done

Impression...

$ gcc rnd.c -o rnd
$ for i in {1..5}; do ./rnd; done
1158880197
501076563
213577277
1251321038
1148335733
2072905546
1342241427
1561109312
380708773
620742083
852878351
1021323199
1918572767
2022993565
1242913309
956395645
2100425479
1520573396
1834768200
693311397

If you comment // for(int i = 0; i<4; i++) in rnd.c it can be used for random date' ...

$ for i in {1..5};do date --date='@'$(./rnd); done 
Mi 19. Dez 03:19:20 CET 1979
Fr 22. Aug 11:56:59 CEST 1980
Di 13. Jul 17:47:54 CEST 1982
Fr 3. Mai 19:59:37 CEST 2002
Fr 27. Apr 09:33:41 CET 1979
koyaanisqatsi
  • 2,585
  • 2
  • 8
  • 15