# Can someone help me with code to generate random numbers in a range of say 50-85?

• 11-22-2001
Robert_Ingleby
Can someone help me with code to generate random numbers in a range of say 50-85?
How do I write simple code to generate random numbers in a range?
• 11-22-2001
cody
http://www.cprogramming.com/cboard/s...6225#post39747

This is not a crosspost :rolleyes: :)
• 11-22-2001
Garfield
Just use rand() and then add the amount (50 in this case) you want the range to start at.

--Garfield
• 11-22-2001
kwigibo
n = 50 + rand() % (85-50+1);

NOTE: rand() function is pseudo random, you may seed the rand() function using srand() function something like this

srand(time(NULL));
n=50+rand()%(85-50+1);

correct me if im wrong. as it has been a while since I used this function.

Best of Luck
• 11-22-2001
Garfield
What do you mean, "seed the rand() function"?
• 11-22-2001
QuestionC
The random function doesn't just pick a number out of thin air, it has to perform some math on the currently seed, and generally it then replaces it's seed with the generated number.

So... if the user knows what the seed is, then all of a sudden your random numbers ain't so random anymore, so you need a random seed. Obviously, you can't use the rand function for this. As far as I know, there are two good ways to generate numbers 'random enough' to be seed values. One is time, and the other is temperature.
• 11-22-2001
Garfield
hmmm...that makes sense.

--Garfield
• 11-22-2001
QuestionC
Code:

```#include <stdlib.h> #include <stdio.h> #include <limits.h> int main () {  int i;  printf ("INT_MAX: %d\nRAND_MAX: %d\n\n", INT_MAX, RAND_MAX);  printf ("--0--\n");  srand(0);  for (i = 0; i < 10; i++) printf ("%d ", rand());  printf ("\n\n");  printf ("--0--\n");  srand(0);  for (i = 0; i < 10; i++) printf ("%d ", rand());  printf ("\n\n");    srand(0);  rand();  srand (i = rand());  printf ("--%d--\n", i);  for (i = 0; i < 10; i++) printf ("%d ", rand());  printf ("\n\n");  srand(0);  rand();  srand (i = rand());  printf ("--%d--\n", i);  for (i = 0; i < 10; i++) printf ("%d ", rand());  printf ("\n\n");  return 0; }```
Network issues prevent me from actually compiling this code, so feel free to add semicolons and marks of parenthesis as needed.

The point of using time to seed rand is so that the same string of random numbers cannot be generated in two different runs of the program.
• 11-22-2001
novacain

If you make multiple calls on the rand, don't seed with the same seed again. Better yet do it once on init. As the numbers are a list and PC's are so fast it may be you get the same series of 'random' numbers if you use the time.
• 11-23-2001
bigtamscot
Code:

```/*more appropriate */ num = (rand() %35) + 50;```
• 11-23-2001
Stoned_Coder
that max's at 84 not 85 bigtamscot.....

correctly is

num = (rand() %36) + 50;