-3

How to generate random number within x-y range in C where

X : [t , t+m] and Y : [r , r+m ].

That is , if x varies from t to t+n and y varies from r to r+n.

Rishabh Agarwal
  • 2,374
  • 1
  • 21
  • 27
  • 1
    http://stackoverflow.com/questions/2509679/how-to-generate-a-random-number-from-within-a-range – Mike Feb 02 '15 at 21:09
  • @Mike Disagree that the post is a good duplicate as that one is about integers and this is FP - subtle difference, even though the over-all math is the same. Likely a dupe exist elsewhere though. – chux - Reinstate Monica Feb 02 '15 at 22:03
  • This is not a duplicate question. It seems to be similar but it is different. Don't just go on title please read the question carefully before adding wrong links – Rishabh Agarwal Mar 16 '17 at 19:41

2 Answers2

1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
   double x = 1.0;
   double y = 2.0;
   srand(time(NULL));

   // Guarenateed keep x1 between x and y.
   double x1 = x + rand()*(y-x)/RAND_MAX;

   printf("x1: %lf\n", x1);

   return 0;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Basically you seed the generator with operation system ticks count, modulo your generated number with the upper range and add the lower range to the result.

Roman Ambinder
  • 369
  • 3
  • 7