I just wondering is there any possible way to use rand() in a function to generate a random?

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int get_random(void);

int
main(void){
    int i;
    for(i=0;i<=5;i++){
        printf("%d\n",get_random());
    }
    return 0;
}

int
get_random(void){
    srand((unsigned)time(NULL));
    int x;
    x = rand()%2;
    return x;
}

I run above code and generate the same number everytime!!!
Is there any way to generate a random within a function (e.g. get_random) ?
NOTE: I don't wanna put srand((unsigned)time(NULL)); in my main(void) function!!!

rand() isn't very good for random numbers, but your main problem is using srand() multiple times.

You need to set it only once, or it will keep generating duplicate numbers, this is because when you set the seed, rand() "resets". Because the seed always generates the same pattern, you will end up with the same number all the time.

The reason they never change when you start the program is because not even 1 second passes when you run it. Which is why when you open it one second later it suddenly changed slightly.

Here's a workaround, if you don't want to put srand in your main function you can do something like this:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void get_random(void);

int main(void){
   get_random();
   return 0;
}

void get_random(void){
   int i,x;
   srand((unsigned)time(NULL));
   for(i=0;i<=5;i++){
      x = rand()%2;
      printf("%d\n",x);
   }
   return;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.