I was playing with some code again

``````#include <iostream>
#include <cstdlib>
using namespace std;

int main ()
{
int seed;

cout << "Enter a seed: "; //enter 8
cin >> seed;

srand (seed);

cout <<"A is " << rand () << endl;            //64
cout <<"B is "<<rand () << endl;              //28170
cout <<"C is "<< rand () << endl;             //311
cout <<"D is "<< rand () * rand () << endl;   //803546005

return 0;
}``````

and I was wondering, why does A always print out 64, i didn't see any function that does that in this code snippet, if possible a explanation of how B, C and D derive those values will help alot too.

Sorry to trouble you guys again. :)

If the seed is always the same, the pseudorandom sequence will always be the same. Change the seed to something other than 8, and A will probably be different.

That depends on the algorithm rand() uses. It's probably some form of linear congruential random number generator, but there's so many of those it's impossible to tell what sequence will result without seeing the code or doing a lot of analysis on produced sequences.

## All 5 Replies

If the seed is always the same, the pseudorandom sequence will always be the same. Change the seed to something other than 8, and A will probably be different.

If the seed is always the same, the pseudorandom sequence will always be the same. Change the seed to something other than 8, and A will probably be different.

I was wondering how does it derive 64? Or is there no way to explain it?

That depends on the algorithm rand() uses. It's probably some form of linear congruential random number generator, but there's so many of those it's impossible to tell what sequence will result without seeing the code or doing a lot of analysis on produced sequences.

That depends on the algorithm rand() uses. It's probably some form of linear congruential random number generator, but there's so many of those it's impossible to tell what sequence will result without seeing the code or doing a lot of analysis on produced sequences.

Does that mean the values for B, C and D are randomized too?

Does that mean the values for B, C and D are randomized too?

Well...yes. When you call rand() it gives you the next pseudorandom number in the sequence. The sequence can be reset by calling srand().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.