Random number list

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main()
{
   int i;
   int diceRoll;

   for(i=0; i < 20; i++)
   {
       printf("%d \n", rand());
   }

    return 0;
}

This is the code I wrote in c (codeblocks) to get random numbers, the problem is that I always get the same sequence: 41,18467,6334,26500etc.

I'm still learning, so try explaining how you are talking to 8 year old D:

+4
source share
4 answers

You get the same sequence every time because the seed for the random number generator is not set. You need to call srand(time(NULL))as follows:

int main()
{
    srand(time(NULL));
    ....
+5
source

. , "", "" . , , . , , . , , . , , , - (NULL). , ( ) . , . , (srand (time (NULL)) , , . , . , .

#, ++. ctime. , rand() . #include random , . !

+1

, , <ctime> srand(time(NULL));.

-, , rand(), : rand()% x 0 x-1. , rand() % 6 + 1.

-1

srand((unsigned)(time(NULL)) , .

Modulo rand()%10means that you get any number starting with 0, up to the fact that you are modulo -1. So, in this case 0-9, if you want 1-10:rand()%10 + 1

int main()
{  
    int i;
    int diceRoll;

    srand((unsigned)(time(NULL));

    for(i=0; i < 20; i++)
    {
        printf("%d \n", rand() % 10); //Gets you numbers 0-9
    }

    return 0;
}
-1
source

Source: https://habr.com/ru/post/1649070/


All Articles