Random Number

Feb 4, 2012 at 12:03am
Hello,

For the purposes of an algorithm class that I am taking, we are asked to create an array of random numbers which will be used in a specified function. My question pertains to rand() and srand(). When should I use srand()? How often should it be used? Some of the material I've read online has suggested something of the sort:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstlib>

void getRandom () { 
std::cout << "Random number: " << rand() << std::endl;
}
int main() {

srand(time(0)); // only call once in program?

getRandom();

return 0;
}



Thanks in advance.

L
Last edited on Feb 4, 2012 at 12:13am
Feb 4, 2012 at 12:19am
Use srand() *once* in your program as you have done.
Feb 4, 2012 at 12:21am
Unless you want to reconstruct a specific random number sequence that is.
Feb 4, 2012 at 12:39am
To hanst99,

We are just using the random numbers to simulate possible user input. For example rand()&101 to represent possible grades on an exam.

The srand should be called at the beginning of the program (just after main), correct? I'm looking at creating a class in which the random function will a method of the class. It probably would not be a good idea to insert the srand() into the constructor of this object.
Feb 4, 2012 at 12:44am
closed account (3hM2Nwbp)
Personally, if I'm using the the the random implementation in the std namespace, srand is always the first line in the main method.
Feb 4, 2012 at 12:44am
What if its a random integer between two other integers?
Like TI-Basics randint(lowest,greatest)
Feb 4, 2012 at 12:46am
closed account (3hM2Nwbp)
What if its a random integer between two other integers?


1
2
int rand = lowest + (rand() % (greatest - lowest));
int between5and10 = 5 + (rand() % 5);


* Oi! You're not the OP.
Last edited on Feb 4, 2012 at 12:47am
Topic archived. No new replies allowed.