已关闭,感谢paxdiablo的帮助
如果我正确理解了这个问题,则您不希望四个连续的数字都小于50。您可以通过简单地保持计数并调整行为来实现此目的,如果前三个都是全部,则生成另一个数字少于50。
如果您正在寻找一个独立的C ++函数来做到这一点(给您每个调用一个随机数,并带有特定的附加限制),则可以使用类似的方法:
int getMyRand() {
// Keep track of how many consecutive under-50s already done.
// Careful in multi-threaded code, may need thread-local instead.
static int consecUnder50 = 0;
int number;
// If last three were all < 50, force next one to be >= 50.
if (consecUnder50 == 3) {
number = rand() % 51 + 50; // 50-100 (inclusive).
} else {
number = rand() % 81 + 20; // 20-100 (inclusive).
}
// If less, record it, otherwise restart count.
if (number < 50) {
++consecUnder50;
} else {
consecUnder50 = 0;
}
// Give caller the number.
return number;
}
[在使用此函数之前,请不要忘记为随机数生成器添加种子,并且要知道C ++具有更好的随机数生成器,尽管rand()
通常很好,除非您是统计学家或密码学家:-)