### Random

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.

srand merely seeds the random (sets it up sort of), rand is the actual function call.
So I would use srand before I used rand right?
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.
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
 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.
you can do this:

srand(time(NULL);

x= rand %8;

 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.
Yeah thanks, I should have said greater than or equal to 0 and less than a 100.
 ``123456789101112131415161718`` ``````#include #include int random(int low, int high) { return rand() % (high - low + 1) + low; } int main() { srand(static_cast(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.