LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Random number generator for linux (https://www.linuxquestions.org/questions/programming-9/random-number-generator-for-linux-6474/)

Steve_Taylor 09-12-2001 04:45 PM

Random number generator for linux
 
i have a Random number generatorfor win32 but when i compiled it and ran it on linux it always gave 0 as the generated number but on windows it gives a differnt number!?
can anyone help?


Code:

int num;
srand(time(NULL));
num=(rand()*100)/(RAND_MAX+1);

printf(" rand == %d ",num);


kin 09-12-2001 07:09 PM

hi

try to assign and print out as a double or float and use %f instead of %d, it might help. ;)

Steve_Taylor 09-13-2001 03:17 PM

i tred that it still did not make a differnce

does anyone know of any good randum number generators that if givvena number say 37 would generate a number between 1 and 37??

gluon 09-23-2001 04:44 PM

hi


the main problem of your prog is that you have an overflow!!! Just try something like :





int num;


srand(time(NULL));


return (int) (((double) rand() / (double) RAND_MAX) * (double) limit) + 1;





by

;)

habiblove 09-23-2001 08:39 PM

Anything wrong with using this?



srand(time(NULL));
array[i] = rand() % 1001;

habiblove 09-23-2001 08:44 PM

Sorry about previous post. I am adapting this from previous code.

Anything wrong with using this?


int num;
srand(time(NULL));
num = rand() % 38;
return num;

habiblove 09-23-2001 09:59 PM

Or if you wanted to create a random number from 1 to limit, try this:

int num;
int limit;

srand(time(NULL));

num = (rand() % limit) + 1;

return num;

Steve_Taylor 09-24-2001 02:54 PM

Dont mean to sound stupid but what does the % do i have looked it up in the book that i have and cant find it? well not used in this way.

habiblove 09-24-2001 04:02 PM

The % is called the modulus. It gives you the remainder of dividing two numbers.

Thus, 13 % 10 returns 3. Using this is nice because:

( number % limit ) + 1 always returns a number from 1 through the limit.

gluon 09-25-2001 04:20 AM

OK habiblove,

you're right : modulus seems to be much easier... sorry !


:study: :study: :study:

habiblove 09-25-2001 06:41 PM

It is pretty neat. Who said a college education isn't worth anything?

Steve_Taylor 09-26-2001 12:39 PM

i went to college but din't get all that much out of it

Colonel Panic 09-30-2001 04:21 PM

main()
{
printf("I have no idea!\n")
}

*****Colonel Panic*****


All times are GMT -5. The time now is 11:04 PM.