Kristian Karadjov
Kristian Karadjov

Reputation: 43

How does this expression work: Num*rand() / RAND_MAX?

How does this expression work?

 Num*rand() / RAND_MAX

If, for example, I replace the number with 7.7, it gives me values from 0. to 7. (double).

Upvotes: 2

Views: 2210

Answers (2)

coder-don
coder-don

Reputation: 113

Tagging onto MrGreen's answer, I have found that when n is an integer, I will get an output of 0 when using double val = n * rand()/RAND_MAX;. However, this can be addressed by a slight addition:

double val = (double) n * rand()/RAND_MAX;

Upvotes: 1

MrGreen
MrGreen

Reputation: 499

The rand() function generates an integer value between 0 and RAND_MAX. so rand()/RAND_MAX generates real value between 0 and 1. So in the following code we have
0 <= val <= n where n can be an integer or a real number.

double val = n * rand()/RAND_MAX;

Upvotes: 3

Related Questions