C / C++语言中rand() 每次产生的随机数一样

本文详细介绍了C/C++与Objective-C语言中随机数生成的方法及其实现,包括如何使用srand()和time()初始化随机数种子,以及如何生成特定范围内的随机数。此外,还对比了C++中的rand()与Objective-C中的arc4random()的使用场景与区别。

  C / C++语言中

  rand() 每次产生的随机数一样

  int rand( void );

  [csharp] #include

  #include

  #include

  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

  #include

  #include

  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

  #include

  #include

  using namespace std;

  int main()

  {

  srand((unsigned)time(NULL)); //初始化随机数种子

  for ( int i = 0; i < 10; i ++ ) //产生10个随机数

  {

  cout << rand()%10 << endl;

  }

  return 0;

  }

  

  #include

  #include

  #include

  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); //初始化时,设置下种子就好了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值