# rand()?

This is a discussion on rand()? within the C++ Programming forums, part of the General Programming Boards category; I am making an AI for my ttt game... and im making a test to see if rand() really works... ...

1. ## rand()?

I am making an AI for my ttt game... and im making a test to see if rand() really works... but i run this code...
Code:
```#include <iostream>
#include <stdlib.h>
#include <conio.h>

int main(int argc, char *argv[])
{
int test;

test = rand()%5;
cout << test << "\n";

system("PAUSE");
return 0;
}```
and i always get 1!!!!! why doesnt it work!

2. ## Re: rand()?

You can add this for more checking :
Code:
```#include <iostream>
#include <stdlib.h>
#include <conio.h>

int main(int argc, char *argv[])
{
int test = 0;
int test1 = 3;
test = rand()%5;
test1= rand()%5;

cout << test << "\n";
cout << test1<< endl;
system("PAUSE");	/// COMMENT THIS
return 0;
}```
tell us what happend.

3. ok... i see what happends... but either im stupid or this doesnt help me get a random number between 1 and 5.

4. You didn't seed your random numbers

You must call this before you do random numbers

srand(time(NULL));

- OR -

srand(unsigned(time(NULL)));

you should also include ctime for C++, or time.h if you are using C

5. Here's some code for you to use

Code:
```#include <iostream>
#include <stdlib.h>
#include <conio.h>

int main(int argc, char *argv[])
{
int test = 0;
int test1 = 3;
test = 1 + (rand()%5);
test1= 1+ (rand()%5);

cout << test << "\n";
cout << test1<< endl;
system("PAUSE");	/// COMMENT THIS
return 0;
}```
You must add 1, because the rand() starts at 0. So without the +1 you are saying random number between 0 and 4. You'll learn, almost everything in C++ starts at 0.

6. ^%*\$^%*(\$%@@\$^#^~!~~!!!!!!!
i just deleted my tic tac toe game... it took hours to do!!!

Ohh well... thanks anyway... ill use rand for something else

7. ## Re: rand()?

Originally posted by elfjuice
Rand()?
Maybe you should search the board first before asking something.

8. i tried that before i posted... but i didnt get an answer

9. >i just deleted my tic tac toe game... it took hours to do!!!

What compiler?
If you are using a compiler with an IDE, you may have a backup file. Check for a file with a .bak extension.

10. rand() is a psuedo-random number generator. It will produce the same sequence of "random" numbers with a given seed.
It is common to use time() as the seed number for srand() which is used to seed the number generator.

Without seeding srand() you'll get 41 for your first number from rand(). 41 % 5 = 1.

/* edited: better algorithm for random numbers in link below */

11. What is the difference between rand and random? And which is the best to use?