I need to generate and reuse a 5 digit random number every time my program is executed. But the following generates random numbers every time the function is called.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <time.h>

int RANDOM(void)
{
	int RANDOMNUMBER = 0;

	srand((unsigned int)time(NULL));
	RANDOMNUMBER = rand() % 99999; // create a random 5 digit number to be reused in other functions

	if (RANDOMNUMBER < 10000)
	{
		RANDOMNUMBER = RANDOMNUMBER + 10000; // correction because sometimes the number generated is 4 digits long
	}

	return RANDOMNUMBER;
}

char *ONE(void)
{
	static char ONE1[15] = "";

	sprintf(ONE1, "ONE%.5i", RANDOM());

	return ONE1;
}

char *TWO(void)
{
	static char TWO2[15] = "";

	sprintf(TWO2, "TWO%.5i", RANDOM());

	return TWO2;
}

void THREE(void)
{
	printf("THREE%.5i\n", RANDOM());
}

int main(void)
{
/* A different random number is output every second. This is a problem because the program takes various seconds to execute. How can I reuse a random number every time the program is executed ? */

	puts(ONE());
	sleep(1);
	puts(ONE());
	sleep(1);
	puts(ONE());
	sleep(1);
	puts(TWO());
	sleep(1);
	puts(TWO());
	sleep(1);
	puts(TWO());
	sleep(1);
	THREE();
	sleep(1);
	THREE();
	sleep(1);
	THREE();

	return 0;
}

deleted line 12 -- srand() does that. And its in the wrong place too -- it should appear at the top of main() because srand() should only be called once during the lifetime of the program.

Edited 7 Years Ago by Ancient Dragon: n/a

This article has been dead for over six months. Start a new discussion instead.