I'm trying to understand how the rand() function works. I started out with a simple for loop printing random numbers each time, and that seems to work perfectly, but as soon as I add more code (in this case I'm trying to clamp the random number between 1 and 20, and doing some other stuff to get the probabiliy of two events happening) it stops working and only returns 0s.
Any idea what's happening?
int getRando(int bNumber)
{
int i, r;
while(r>32760)
{
r = rand();
}
for(i=1;i<=bNumber;i++)
{
if (r <= (1638 * i))
{
r = i;
break;
}
}
return r;
}
int main(int argc, char *argv[]) {
srand(time(NULL));
int i, r, primaBianca = 0, primaNera = 0;
for(i=0;i<1000;i++) //this works
{
r = rand();
printf ("%d\n",r);
}
for (i=0; i<1000;i++)
{
r = getRando(20); //from this point on it only returns zeroes
if (r<=12)
{
r = getRando(20);
if (r<=12) primaBianca++;
}
else
{
r = getRando(19);
if (r<=12) primaNera++;
}
}
printf ("prima pallina bianca: %d\n",primaBianca);
printf ("prima pallina nera: %d\n",primaNera);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire