lundi 19 septembre 2016

How to generate casual number without repetitions in c?

In a UDP application i have to make a choice between sending a or discarding a packet to simulate a loss in the network. I thought to generate casual number (0 or 1 ) and then make the choice depending on the extraction. I have used this code : //extract 1 with probability p and 0 with probability 1-p (probability p is intended to be in percentual);

    int randEstrazione(double p){   
        double x,tmp;    
        int n,k;
        srand(time(0));
        n=rand();
        tmp=p/100;
        x=((double)n)/RAND_MAX;
        if(x<tmp){
           k=0;
    }
        else k=1;
        return k;
   }

But it extract the same number on every call of the function . I have red a lot of post on the net but i did not understand how to avoid the problem.




Aucun commentaire:

Enregistrer un commentaire