Rand() gets same seed

I'm trying to get a random number from 0 - 2, but for some reason I keep getting the number 1 being returned and I'm guessing it's because the seed stays the same. Take a look at the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
string AI()
{
	/*
	0 - Rock
	1 - Paper
	2 - Scissors
	*/

	int r = rand() % 3; //returns 0-2
	if (r = 0)
	{
		return "rock";
	}
	else if(r = 1)
	{
		return "paper";
	}
	else
	{
		return "scissors";
          }
}


Every time I call that function r equal's 1. So outside the function, inside of my main function I call:
srand (time_t(NULL));
But that doesn't change anything r still equals 1 whenever I call my AI function.
First problem I see is your if and else if statements. You are making assignments not testing.

1
2
3
4
5
	if (r = 0)
	{
		return "rock";
	}
	else if(r = 1)


Change to:

1
2
3
4
5
	if (r == 0)
	{
		return "rock";
	}
	else if(r == 1)
Ahh that's what it was. I was setting r equal to 1 which would return paper every time. I changed it to the comparison(==) and it works like a charm. Thank you.

Edit - I come from a vb.net background so I'm use to the single equal(=) being used for comparison and setting assignments, so it's taking some effort getting use to the c++ comparison.
Last edited on
Should be: srand (time(NULL));

time_t is a type, like int, so the previous code was just doing srand(0);
@Chervil - Thanks, I'll use the srand (0) and avoid having to include the <time.h>
@Chervil - Thanks, I'll use the srand (0) and avoid having to include the <time.h>


I think you missed his point.

srand(0) will seed your rng with 0 every time... which means every time you run the program you will get the exact same sequence of numbers (ie: your program will be predictable).

seeding with the time helps ensure that the sequence is different every time the user starts up the program.

So yeah... just include <ctime> (it doesn't hurt to do it), and srand with time().
Topic archived. No new replies allowed.