problem with generating random numbers !

S

sugaray

I want to write a school computer billing system, one of the function
is to distribute machine id using rand() for each student log on,
suppose there's 100 machines, when each person log on, the system will
store user's info such as name, student id number, log on time, log
out time into a database file, when the next student log on, the
function loads the database, and compare the random generated machine
id with the existing ids store in the database, I'm using a while-loop
to generate random ids until the generated one differs from all the
existing ones, or the loop ends when no machine id's available. It
seems there's something wrong with my program, the generated random
ids always overlap the existing ones, hope someone will help me out
with this, below is my code:

#define DATABASE "database.dat"
#define GENRAND(n) (rand()%n)
#define UNOCCUPIED -1 // test whether the machine occupied

typedef struct tagRECORD { // the management record structure
char name[8]; // student name
char studentID[9]; // student ID
char logonTime[25]; // log on time
char logoutTime[25]; // log out time
int machineID; // machine ID
clock_t logon; // log on clock
clock_t logout; // log out clock
}RECORD;

const unsigned totalMachine=100; // total machines

int statistics[totalMachine];

void errorMessage(char *msg) { // show error messages
fprintf(stderr,"error: %s\n",msg);
exit(1);
}

int assignID(void) { // distribute the available machine ID randomly
int i,r;
int id=0;
FILE *fp;
RECORD record;

fp=fopen(DATABASE,"rb");
if(fp==NULL) {
errorMessage("assignID()");
}

for(i=0;!feof(fp) && i<totalMachine;++i) {
fread(&record,sizeof(RECORD),1,fp);
statistics=record.machineID;
}

for(r=0;i<i && statistics!=-1;++r) {
id=GENRAND(totalMachine);
while(statistics[r]==id)
id=GENRAND(totalMachine);
}

fclose(fp);

return id;
}

when initialization in main() I assigned -1 to all the elements of
array statistics[], using the value -1 to test whether the machine is
occupied.

for(i=0;i<totalMachine;++i)
statistics=UNOCCUPIED; // initialize the array
 
T

Tom Zych

sugaray said:
seems there's something wrong with my program, the generated random
ids always overlap the existing ones, hope someone will help me out
with this, below is my code:

That behavior immediately suggests to me that you're not seeding the
rng with a new value between runs. rand() repeats the same sequence
unless it's seeded with a different number. Try this:

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top