#### Archived

This topic is now archived and is closed to further replies.

# Srand() and rand() help

This topic is 5688 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm having some problem remembering things to do with the above and I don't have my text book with me to check it up so thought you guys could help. First of all in C, what library do I include to use srand() and rand(). If I remember rightly I need to also include time.h to use the time in seeding the generator but can't remember what the syntax for srand() is. Am I correct in saying that if I wanted a number from 0 to 10 after srand() has been used the code would be number = rand() %10; and if I want from 10 to 20 it is number = (rand() %20) +10; Help Please!!! [edited by - SteveBe on July 30, 2002 10:02:35 AM]

##### Share on other sites
Off the top of my head:
#include "stdlib.h"

The syntax is (if you are writing a windows app)
srand((unsigned)GetTickCount())

To get a number between 0 and 10 you
number = rand() % 11 ;

a random number between 10 and 20 would be
number = (rand() % 11) + 10;

D.V.

Carpe Diem

##### Share on other sites
Thanks DeltaVee but I''m such a newbie I''m not using windows applications yet. I''m doing it all in boring old dos!!!!!

So if anyone else can tell me how to seed the generator for a dos program using time.h I''d be very grateful.

And thanks for correcting me on my rand() syntax.

##### Share on other sites
time_t time( time_t *timer );

time_t is just a long so ...

long t;

time(time_t *)&t);
srand((unsigned)t)

D.V.

Carpe Diem

##### Share on other sites
Or even shorter:

srand((unsigned)time(NULL));

There are better ways to distribute random numbers. Search around on the forums. It comes up quite often.

/*=========================================*/
/* Chem0sh */
/* Lead Software Engineer & Tech Support */
/* http://www.eFaces.biz */
/*=========================================*/