Well rand is actually pseudo-random. So it needs some form of randomness to start it's algorithm, in this case time(0) is the number of seconds since like january 1st 1970 (or something like that, been a while)
Otherwise, if you don't seed the random number generator, you would get exactly the same numbers every time you ran your program!
edit:
@Bazzy : muahaaha, but you tend to post more detailed and thought out answers ;)
srand seeds the pseudo-random number generator.
An example implementation would be:
1 2 3 4 5 6 7 8 9 10 11 12
int previous;
int rand()
{
next = next * A + B; // A and B are magic numbers
return previous;
}
void srand ( int i )
{
previous = i;
}
The point is, rand generates the next number based on the previous one ( and some magic values ), srand sets that to a fixed value. time returns the numbers of seconds since Jan 1st 1970, for details see http://www.cplusplus.com/reference/clibrary/ctime/time/
[Edit]
@ultifinitus
LO, you keep posting few minutes before me
rand does not give a truly random set of numbers, if you seed it with a certain number, and use that same number to seed it every time, it will give the same sequence of numbers when you call rand(). Because of this, you want ideally to seed the random with a random number, a decent substitute for this is the current calendar time, which is what time(NULL); gives you.
That's it basically, you're seeding the random with the current calendar time, to obtain a randomish sequence of numbers. Computers aren't good in general at making random numbers, and rand() is also not a great way of getting random numbers but for most applications that beginners will want to make it is good enough.
EDIT - wow it took me 5 minutes to write that? I need to get my game together
// Jeremy Williams
#include "stdafx.h"
#include <string>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
usingnamespace std;
int _tmain(int argc, _TCHAR* argv[])
{
srand ( time(NULL) );
string go = "true";
string alph = "abcdefghijklmnopqrstuvwxyz";
string word = "";
int randNum = rand() % 24 + 1;
char letters[24];
char letter;
cout << "Enter a letter: ";
getline(cin, word);
for(int i = 0; i < 24; i++)
letters[i] = alph.at(i);
while(go != "false")
{
cout << "Enter a letter: ";
getline(cin, word);
if(word.length() > 1)
cout << "Please enter only one letter." << endl;
else
{
//working on program here
}
}
return 0;
}
are you saying that the srand ( time(NULL) ); is getting a random number from some time from 40 or so years back and that the int randNum = rand() % 24 + 1; just modifies that with an algorithm so it will be a random number from 1 - 24.
if i am right on that, thank you for your help. if not, well i guess i need to stay in school ha ha.
EDIT:
Couldn't get the [code\] right... used '\' instead of '/'