D
D
dworff2020-01-30 11:29:21
C++ / C#
dworff, 2020-01-30 11:29:21

How to correctly set the range of random numbers with the rand function?

There is an array of 1000 elements. I need to set the interval a,b where a and b are random numbers. But at the same time, the interval should not "drop in" beyond the border of my array of 1000 elements.

for (int i =1; i<=1000; ++i) //кол-во запросов 
{
   int a = rand() % 1000;
   int b = rand() % 1000;

   if (a > b) {
      int tmp_b = b;
      b = a;
      a = tmp_b;
   }

But, I was told that int a = rand() % 1000; not true, because goes beyond the bounds of the array.
I figured out the rand function and calculated using the formula max-min + 1 and it came out to me anyway 1000 ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vanyamba-electronics, 2020-01-31
@vanyamba-electronics

int a = 999 * rand() / RAND_MAX;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question