C / C++語言中
rand() 每次產生的隨機數一樣
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() 可使每次產生的隨機數不同,和rand連用
[cpp] #include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand((unsigned)time(NULL)); //初始化隨機數種子
for ( int i = 0; i < 10; i ++ ) //產生10個隨機數
{
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)); //初始化隨機數種子
for ( int i = 0; i < 10; i ++ ) //產生10個隨機數
{
cout << rand()%10 << endl;
}
return 0;
}
Objective-C語言中
arc4random() 比較精確不需要生成隨即種子
使用方法:
[cpp] arc4random() //隨機產生任何數
arc4random()%x //產生0~x之間的隨機數
(arc4random()%x )+1 //產生1~x之間的隨機數
arc4random() //隨機產生任何數
arc4random()%x //產生0~x之間的隨機數
(arc4random()%x )+1 //產生1~x之間的隨機數
random() 需要初始化時設置種子
使用方法:
[cpp] srandom((unsigned int)time(time_t *)NULL); //初始化時,設置下種子就好了。
srandom((unsigned int)time(time_t *)NULL); //初始化時,設置下種子就好了。