ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I am trying to generate two random numbers using random(), but it always returns 4 and 7 for me. I am using % in the rnd() function so I get only numbers between 1 and max. Thanks for the help
Here is the code:
Code:
#include <stdio.h>
int main()
{
int rnd( int max) {
return ( random () % max) +1;
}
int valor1, valor2, max;
max = 30;
valor1 = rnd(max);
valor2 = rnd(max);
return 0;
}
The function random() (and also rand() ) have a very large sequence of random number, from which they return the next in the sequence every time random() (or rand() ) is called.
The "problem" is that when your program starts random() starts at the same place in the sequence of random numbers, so every time you run your program you get the same "random" numbers.
The solution is that you can tell the random system where in the sequence to start. To do this, use the srandom() function (or resp. the srand() function if you use rand() instead of radom() ).
So you need to call srandom() with a number that is not the same every time you run your program. One common way is to use the time() function, which return the numbers of seconds since 00:00:00 UTC, January 1, 1970.
The current time (in seconds) -as you can imagine- is different every time you start the program. So call "srandom(time(0))" just once at the start of the program.
Here's your program fixed:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int rnd( int max) {
return ( random () % max) +1;
}
int main()
{
int valor1, valor2, max;
max = 30;
srandom(time(0));
valor1 = rnd(max);
valor2 = rnd(max);
printf("valor1 = %d\n", valor1);
printf("valor2 = %d\n", valor2);
return 0;
}
The other thing about the sequence is that the second value you called will always be the next one in the sequence from the first one. For most things it won't be a problem, but if you are writing some dumb dice simulator for some dumb tutorial (has anyone on a computing course NOT written a dice simulator?) and you want the numbers to match up now and again, you'll have to do the whole thing over again to generate the second number, etc. What fun.
I would suggest one minor emendation to the program:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int rnd(int max) {
int temp, value;
do {
temp = random ();
value = temp % max + 1;
} while (temp >= RAND_MAX - RAND_MAX % max);
return value;
}
int main()
{
int valor1, valor2, max;
max = 30;
srandom(time(0));
valor1 = rnd(max);
valor2 = rnd(max);
printf("valor1 = %d\n", valor1);
printf("valor2 = %d\n", valor2);
return 0;
}
The added "while" condition prevents the returned value from being (slightly) biased if the range of output values of random() is not a multiple of the modulus.
If I were using a Linux system and needed good random numbers I'd use /dev/random or /dev/urandom as a seed. I wrote a program like this some time ago, here:
Code:
// includes
#include <stdio.h>
#include <stdlib.h>
// defines
#define NUM_RAND 10
// main
int main(void)
{
// init vars
unsigned seed = 0; // random seed
// ! init vars
FILE *urandom; // file handle for /dev/urandom
unsigned int i; // all-purpose counter
urandom = fopen("/dev/urandom", "rb"); // open /dev/urandom as readonly binary
if (urandom == NULL) // did it open ?
{
perror("!!! ERROR: could not open /dev/urandom for reading !!!");
exit(1); // fail
}
// read the one seed from urandom
if (fread(&seed, sizeof(int), 1, urandom) < 1) // did it read ?
{
perror("!!! ERROR: failed to read from /dev/urandom !!!");
exit(1); // fail
}
// we are now finished reading from /dev/urandom, close it
fclose(urandom);
// print the seed just to make sure
printf("The seed obtained from /dev/urandom is %u\n", seed);
// seed rand with seed
srand(seed);
// generate some random numbers
for (i = 1; i <= NUM_RAND; i++)
{
printf("Random number #%d, is %d\n", i, rand());
}
printf("%d\n",sizeof(int));
// success
return 0;
}
I'm not a very good programmer, but it seems to work.
Last edited by H_TeXMeX_H; 09-11-2010 at 10:39 AM.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.