Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use rand() to generate numbers in a range? [duplicate]

Tags:

c

random

max

min

Possible Duplicate:
Generate Random numbers uniformly over entire range
How to use rand function to

Could anyone tell me how to use the rand() function in C programming with 1 = min and
7 = max, 1 and 7 included.

Thanks

like image 869
Slrs Avatar asked Dec 02 '22 01:12

Slrs


2 Answers

This will do what you want:

rand() % 7 + 1

Explanation:

  • rand() returns a random number between 0 and a large number.

  • % 7 gets the remainder after dividing by 7, which will be an integer from 0 to 6 inclusive.

  • + 1 changes the range to 1 to 7 inclusive.

like image 161
RichieHindle Avatar answered Dec 05 '22 00:12

RichieHindle


Use the modulo operator. It returns the remainder when dividing. Generate a number in range 0 to 6 by using rand() % 7. Add 1 to that to generate a number in range 1 to 7.

like image 36
Michel Avatar answered Dec 05 '22 01:12

Michel