Hidden Lynx
Hidden Lynx

Reputation: 69

A program about calculate the frequency of two students of a class have the same birthday

My problem is why the output at last is only 0 or 10000?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
    int arr[30],i,j,k,res,num=0,flag=0;
    for(k=0;k<10;k++)     //the number of calculate
    {
        flag=0;
        srand((unsigned int)time(NULL));
        for(i=0;i<30;i++)
        {
            if((res=rand()%365)>32485)    //except the date bigger than 32485
                i--;
            else
                arr[i]=res%365;
        }
        for(i=0;i<29;i++)
        {
            for(j=i+1;j<30;j++)
                if(arr[i]==arr[j])
                {
                    flag=1;
                    break;     
                }
            if(flag==1)
            {
                num+=1;    //if find the same two,add number and break
                break;
            }
        }
    }
    printf("%d\n",num);     //why here is 0 or 10000 rather than other output?
    return 0;
}

Upvotes: 0

Views: 47

Answers (2)

Lee Duhem
Lee Duhem

Reputation: 15121

printf("%d\n",num); //why here is 0 or 10000 rather than other output?

If you add some statement to output arr after you initialized it (after changed that if((res=rand()%365)>32485) to if((res=rand())>32485), of course), you will find out you are using the same arr almost every time, because your iteration is so fast that it will finish far less that one second, so you are using the same random seed almost every time.

You could fix it by moving that srand(..) out of the enclosing for loop, do something like

srand((unsigned int)time(NULL));
for(k=0;k<10;k++)     //the number of calculate
{

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96258

You're using a PRNG, you supposed to initialize it (srand) only once.

At the moment, you generate the same "random" number, again and again...

Note: instead of storing the days, store the counts for each day. It will give you a much cleaner code.

Also, learn to name things. variable names like arr, flag, num, res give almost zero clue about what those variables supposed to store. How about something more informative like day?

Upvotes: 1

Related Questions