In C/C ++
Rand () generates the same random number each time.
Int rand (void );
[Csharp] # include <stdlib. h>
# Include <stdio. h>
# Include <time. h>
Int main (void)
{
Int I;
// Seed the random-number generator with current time so that
// The numbers will be different every time we run.
//
Srand (unsigned) time (NULL ));
// Display 10 numbers.
For (I = 0; I <10; I ++)
Printf ("% 6d \ n", rand ());
Printf ("\ n ");
// Usually, you will want to generate a number in a specific range,
// Such as 0 to 100, like this:
{
Int RANGE_MIN = 0;
Int RANGE_MAX = 100;
For (I = 0; I <10; I ++)
{
Int rand100 = (double) rand ()/
(Double) RAND_MAX) * RANGE_MAX + RANGE_MIN );
Printf ("% 6d \ n", rand100 );
}
}
}
# Include <stdlib. h>
# Include <stdio. h>
# Include <time. h>
Int main (void)
{
Int I;
// Seed the random-number generator with current time so that
// The numbers will be different every time we run.
//
Srand (unsigned) time (NULL ));
// Display 10 numbers.
For (I = 0; I <10; I ++)
Printf ("% 6d \ n", rand ());
Printf ("\ n ");
// Usually, you will want to generate a number in a specific range,
// Such as 0 to 100, like this:
{
Int RANGE_MIN = 0;
Int RANGE_MAX = 100;
For (I = 0; I <10; I ++)
{
Int rand100 = (double) rand ()/
(Double) RAND_MAX) * RANGE_MAX + RANGE_MIN );
Printf ("% 6d \ n", rand100 );
}
}
}
Srand () can make the random number generated each time different, used with rand
[Cpp] # include <iostream>
# Include <stdlib. h>
# Include <time. h>
Using namespace std;
Int main ()
{
Srand (unsigned) time (NULL); // initialize the random number Seed
For (int I = 0; I <10; I ++) // generates 10 random numbers.
{
Cout <rand () % 10 <endl;
}
Return 0;
} <SPAN style = "COLOR: # ff0000">
</SPAN>
# Include <iostream>
# Include <stdlib. h>
# Include <time. h>
Using namespace std;
Int main ()
{
Srand (unsigned) time (NULL); // initialize the random number Seed
For (int I = 0; I <10; I ++) // generates 10 random numbers.
{
Cout <rand () % 10 <endl;
}
Return 0;
}
In Objective-C Language
Arc4random () is more accurate and does not need to be generated immediately.
Usage:
[Cpp] arc4random () // randomly generates any number
Arc4random () % x // generates 0 ~ Random Number between x
(Arc4random () % x) + 1 // generate 1 ~ Random Number between x
Arc4random () // randomly generates any number
Arc4random () % x // generates 0 ~ Random Number between x
(Arc4random () % x) + 1 // generate 1 ~ Random Number between x
Random () sets the seed when Initialization is required
Usage:
[Cpp] srandom (unsigned int) time (time_t *) NULL); // set the seed during initialization.
Srandom (unsigned int) time (time_t *) NULL); // set the seed during initialization.