K
K
kate2018-06-06 00:29:29
C++ / C#
kate, 2018-06-06 00:29:29

How to calculate the rand() function?

Initially, I set the boundaries of the segment. Then it must be written to a function.
For example, for the interval [-5., 5.] the function will look like this:

double random()										
{
  return (double) (-5.0) + (double)rand() / RAND_MAX * 10.0 ; // a = -5; b = 10
}

But I don’t understand how to make it so that I set the boundaries of the interval myself and everything is calculated in the function itself. Help me please.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
devalone, 2018-06-06
@devalone

inline int getRandomNumber(int start, int end) {
  return start + rand() % (end - start);
}

valid for getRandomNumber(10, 20);
rand() generates a number up to RAND_MAX,
% (end - start) "cuts off" (the remainder of the division) to 10, i.e. 555 % 10 = 5
start + shifts by 10 But it's better not to use rand
, but to use modern solutions https://stackoverflow.com/a/7560564/7458932
a whole separate header with a bunch of other generators
and for double https://stackoverflow.com/a/9324796/7458932

N
Nikita, 2018-06-06
@vasilek-nik

double random(int a, int b)										
{
  return (double) a + (double)rand() / RAND_MAX * (b-a) ; 
}

Yes, just like you. Only the numbers a and b were added to the function parameters. The length of the range is calculated as the difference between the end and the beginning.
Usage example:
PS if necessary, a, b can be made double

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question