Clarify rand()

I am using the rand() function, but I need to create a range. Can someone clarify ranges?

1
2
3
4
5
6
7
8
9
10
11
12

#include <iostream>
#include <cmath>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

int main()
{
int x
x = rand() //I want this number to be in the range of -12 to +12
}
http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

Firstly, you need to seed the rand() function with srand(). Computers don't really know how to call random numbers.

initialize a random seed number with
srand(time(NULL)); // This code gives the current time to srand()

To get a range between numbers you use the modulo operator.
x = rand() % 10 ; // This will give you a number between 0 to 9


x = rand() % 10 + 1; // This will give you a number between 1-10

To get a random number is another problem because rand() gives you a number from 0 to RAND_MAX.
x = rand() % 13; // For range from 0 to 12


x = rand() % 2 == 0 ? x : -x; // This last code says if a random number is generated and is even then, give it a positive number, if not then change it to negative


HTH

P.S. Don't forget to include ctime or time.h

Last edited on
Topic archived. No new replies allowed.