Random number during loop [C programming]

I am trying to generate 2 random numbers (between 0-4 and 0-10) each time the loop happens, but it always gives the same number. If I run the program multiple times, it gives different numbers, but the while loop always generates the same 2 numbers. thank.

int random(int range){
    int num;
    srand(time(NULL));
    num = rand() % range;
    return num;
}

int main(){

    int cnt = 0;
    int i;  
    int j;
    while (cnt <= 20) {
        i = random(5);
        j = random(10);
        printf("%d\n",i);
        printf("%d\n",j);
        printf("\n");
        cnt += 1;
    }
    return 0;
}

      

+3


source to share


2 answers


You only need to split the random number generator.

So, run this line outside of your random function:

srand(time(NULL));

      



.. in your main function:

int random(int range){
    int num;
    num = rand() % range;
    return num;
}

int main(){
    int cnt = 0;
    int i;    
    int j;

    // Seed random number generator
    srand(time(NULL));

    while (cnt <= 20){
        i = random(5);
        j = random(10);
        printf("%d\n",i);
        printf("%d\n",j);
        printf("\n");
        cnt += 1;
    }
    return 0;
}

      

+10


source


You only need to split the random function once. Include library time.h and use



#include<time.h>
.....
srand(time(NULL));

      

0


source







All Articles