help using rand()?! producing 8 everytime?!

so i am trying to produce a simple conole game, the high or low game that im sure most of you have seen before. problem is, when i use the rand() function it produces 8 every time, rather than producing a random number. here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
#include<cstdlib>
using namespace std;

int main(void)
{
	int iWinNumber;
	int iGuess;
	int iNumGuesses;
	
	iNumGuesses = 0;
	iWinNumber = (rand()%100)+1;
	
	do
	{
		cout << "Enter your guess!" << endl;
		cin >> iGuess;
		iNumGuesses++;
		
		if (iWinNumber > iGuess) cout << "Guess Higher!" << endl;
		if (iWinNumber < iGuess) cout << "Guess Lower!" << endl;
	} while (iWinNumber != iGuess);
		
		cout << "You guessed correct!\nIt took you "
		<< iNumGuesses
		<< " guesses to guess correctly.\nThe number was "
		<< iWinNumber
		<< "!\nGreat Job!" << endl;
	return 0;
}


iWinNumber is always 8. what am i doing wrong? thanks in advance.
ironically, rand() produces the same number every time you run your program.

Unless, that is, you seed it. Put this line in your code. It can go anywhere, as long as you call it before you call rand().
 
srand(time(NULL));

you'll need to #include <ctime> too.
well thats interesting. it works great now. thanks. :) any quick/easy answer as to why it does that?
Well, this is my understanding of it:
No matter how many times you start your program, the default "seed value" for rand() is invariably the same. If the seed value stays the same, then so will your sequences of random numbers.

This is why you need to use srand()- it changes the seed value. srand(time(NULL)) means that you're changing the seed to the current time. That way, your seed doesn't stay the same- its value will change depending upon the time.
Topic archived. No new replies allowed.