User forums > General (but related to Code::Blocks)
random function question
Deamon:
Hi folks,
under Borland i used the:
randomize();
random(9);
to get a random value betwin 0 and 9 but when i try to compile it under WingW i realize again that it's not ansi compliant. Now my question is how can i achieve the same results in an ansi compliant way ?
regards,
Deamon
takeshimiya:
C version:
--- Code: (cpp) ---#include <stdlib.h>
#include <stdio.h>
#include <time.h>
srand(time(NULL));
int i;
for(i = 0; i < 10; i++)
printf("Random number #%d: %d\n", i, rand());
--- End code ---
C++ version:
--- Code: (cpp) ---#include <cstdlib>
#include <iostream>
#include <ctime>
std::srand(std::time(0));
for(int i = 0; i < 10; i++)
std::cout << "Random number #" << i << ": " << std::rand() << std::endl;
--- End code ---
The function srand() is used to seed the random sequence generated by rand(). For any given seed, rand() will generate a specific "random" sequence over and over again.
TDragon:
In addition to Takeshi's helpful post (neither of your samples will compile, Takeshi :?), allow me to add this:
--- Code: (cpp) ---#include <stdlib.h> // if using C++, #include <cstdlib>; may not be necessary in C
#include <time.h> // if using C++, #include <ctime>
// Seed the RNG
srand(time(0));
int RandomIntInRange(int low, int high)
{
return (int)(rand() / (RAND_MAX / (double)(high - low))) + low;
}
--- End code ---
There's probably an unnecessary cast in there, but don't disparage my parentheses -- I use them to indicate my thought processes when I come back to the code a few years down the road.
takeshimiya:
--- Quote from: TDragon on April 04, 2006, 12:21:27 am ---In addition to Takeshi's helpful post (neither of your samples will compile, Takeshi :?)
--- End quote ---
Sorry, forgot to add #include <time.h> for the first example.
The second example compiles fine, why do you say it'll not compile?
TDragon:
Because it didn't #include <ctime> at the time I made my post.
Navigation
[0] Message Index
[#] Next page
Go to full version