C++生成随机数

1,一般情况,生成随机数采用以下方式:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
  int iSecret, iGuess;
  /* initialize random seed: */
  srand ( time(NULL) );
  /* generate secret number: */
  iSecret = rand() % 10 + 1;
  do {
    printf ("Guess the number (1 to 10): ");
    scanf ("%d",&iGuess);
    if (iSecret<iGuess) puts ("The secret number is lower");
    else if (iSecret>iGuess) puts ("The secret number is higher");
  } while (iSecret!=iGuess);

  puts ("Congratulations!");
  return 0;
}

2,但是实际这种方式生成的随机数并不是很随机,有时候随机变化的幅度很小,而《Accelerated C++》提供了一种不错的方式:

// return a random integer in the range `[0,' `n)'
int nrand(int n)
{
	if (n <= 0 || n > RAND_MAX)
		throw domain_error("Argument to nrand is out of range");
	const int bucket_size = RAND_MAX / n;
	int r;
	do r = rand() / bucket_size;
	while (r >= n);
	return r;
}

3,上面这种方式比较完美,但是稍微有一点不足,那就是只是生成小于RAND_MAX(32767)的随机数,《Accelerated C++》练习题中提供了一种改进的方式:

#include <cmath>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <limits.h>
using namespace std;

#define MY_RAND_MAX 32767

int nrand(int n) {
  if (n <= 0)
    throw domain_error("Argument to nrand is out of range");
  int r;
  if (n <= MY_RAND_MAX) {						       
    const int bucket_size = MY_RAND_MAX / n;
    do {
      int bucket = rand() / bucket_size;
      r = bucket;
    } while (r >= n);
  } else {
    const int bucket_size = ceil(n / MY_RAND_MAX);
    do {
      const int bucket = nrand(MY_RAND_MAX);
      const int remainder = nrand(bucket_size);
      r = (bucket - 1) * bucket_size + remainder;
    } while (r >= n);
  }
  return r;
}

int main() {
  int limit;
  while (cin >> limit)
    cout << nrand(limit) << endl;

  return 0;
}

这种方式真的接近完美了,只是算法稍微复杂点。





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值