Rand() Stuff

Hello i have a question about the rand() function.

when i cout<< rand(); it gives me some same number everytime program is run.

however when i say int randomNum = rand();

i get a different number when the program is run. Any ideas?
Are you seeding the generator? (Use srand()).
In case you don't get the idea from @firedraco here is an example:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <cstdlib> 
#include <ctime> 
using namespace std;
 
int main() { 
    srand((unsigned)time(0)); 
    int random_integer = rand(); 
    cout << random_integer << endl; 
}

What i meant was. since i said int x = rand(); I expected it to be the same as rand(); but it wasnt
ok ok heres whats really wrong i guess;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int main()
{
    int x;
    srand((unsigned)time(0));
    x = rand();
    while (1)
    {
        cout << x;
        cin.ignore();
    }

}



that will display the same number every time i press enter.

I want a pseudo random number every time.

if i replace X with rand() i will get a pseudo random number every time. Why?
Because the call to rand() produces the random number.

1
2
3
4
5
6
    x = rand();  // this generates 1 random number and puts it in 'x'
    while (1)
    {
        cout << x;  // this prints whatever is in 'x'.  It does not change 'x'
        cin.ignore();
    }


Say for example, rand() produces the number 156. That means x=156.

When you loop, you're printing x (156). Since you never change the contents of x, you'll keep printing 156 over and over.

On the other hand, if you move the call to rand() inside the loop, then you'll get a different number:

1
2
3
4
5
6
    while (1)
    {
        x = rand();  // now x is set to a new random number every time the loop runs
        cout << x;  // so this will print different numbers each time
        cin.ignore();
    }
Right! okay thanks thats what i was starting to think. /lick
Topic archived. No new replies allowed.