I am using the rand() function, but I need to create a range. Can someone clarify ranges?
using namespace std;
x = rand() //I want this number to be in the range of -12 to +12
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
P.S. Don't forget to include ctime or time.h
Last edited on
Topic archived. No new replies allowed.