[try Beta version]
Not logged in

 
Random

Sep 11, 2008 at 5:13pm
I have a question. I was looking at a script and it used "rand" as a function but it did not declare it. I thought that this was not a function and that you had to use srand. Please tell me if it a function or not.

Sep 11, 2008 at 5:29pm
srand merely seeds the random (sets it up sort of), rand is the actual function call.
Sep 11, 2008 at 6:50pm
So I would use srand before I used rand right?
Sep 11, 2008 at 7:17pm
yes, but only once.
If you didn't use srand, rand would return the same values every time you called it. Not the same value for multiple calls necessarily, but the same pattern.
Sep 12, 2008 at 1:25am
Well, I don't really know about srand so I can't help with that; however, you can use rand() to generate random numbers.
Just include the header file cstdlib and say for example:
int x;
x = rand(); // which would generate a number between 0 and 32767

If you want it to be between a certain interval you can use
x = rand() % 100; // which would for instance generate a random number btw 0 and 100

It is also possible that each time you use the function it generates the same random number everytime. In that case you can use the function time of the header file ctime and write:
x = (rand() + time(0)) % 100;
Last edited on Sep 12, 2008 at 3:36am
Sep 12, 2008 at 3:01am
It is also possible to each time you use that that function it generates the same random number everytime. In that case you can use the function time of the header file ctime and write:
x = (rand() + time(0)) % 100;
See:
If you didn't use srand, rand would return the same values every time you called it. Not the same value for multiple calls necessarily, but the same pattern.
Sep 12, 2008 at 3:32am
you can do this:

srand(time(NULL);


x= rand %8;


Sep 12, 2008 at 4:16am
x = rand() % 100; // which would for instance generate a random number btw 0 and 100


Actually it would create a random number between 0 and 99. Remember, modulo is the remainder, and you can't have a remainder of 100 in a division by 100.
Sep 12, 2008 at 6:31am
Yeah thanks, I should have said greater than or equal to 0 and less than a 100.
Sep 14, 2008 at 3:05am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <ctime>

int random(int low, int high) {
    return rand() % (high - low + 1) + low;
}

int main() {
    srand(static_cast<unsigned int>(time(0)));

    std::cout << "Dice roll 1: " << random(1, 6) << std::endl;
    std::cout << "Dice roll 2: " << random(1, 6) << std::endl;
    std::cout << "Dice roll 3: " << random(1, 6) << std::endl;
    std::cout << "Dice roll 4: " << random(1, 6) << std::endl;
    std::cout << "Dice roll 5: " << random(1, 6) << std::endl;

    return 0;
}


If <ctime> doesn't work try <ctime.h>
Topic archived. No new replies allowed.