【问题标题】:rand() produces numbers above set range in recursive functionrand() 在递归函数中产生高于设定范围的数字
【发布时间】:2019-03-20 00:26:06
【问题描述】:

我的理解是,这会产生一个介于 10 和偏移量之间的随机数:

random = (rand() % 10) + offset;

offset 增加 1 但永远不会超过 10,但是当我运行此代码时,变量 random 被设置为数字 > 10。

有问题的代码:

#include "pch.h"
#include <cstdlib>
#include <Windows.h>
#include <iostream>
using namespace std;

void gen(int offset)
{
    int random;

    if (offset != 10)
    {
        random = (rand() % 10) + offset;
        cout << "random should be between: " << 10 << " and " << offset << endl;
        cout << "random: " << random << endl << endl;
        Sleep(500);
        gen(++offset);
    }
}

int main()
{
    srand(373);

    gen(1);
    cin.get();
}

和输出:

随机数应该在:10 到 1 之间

随机:7

随机数应该在:10 到 2 之间

随机:11

随机数应该在:10 到 3 之间

随机:3

随机数应该在:10 到 4 之间

随机:13

随机数应该在:10 到 5 之间

随机:10

随机数应该在:10 到 6 之间

随机:13

随机数应介于:10 到 7 之间

随机:16

随机数应该在:10 到 8 之间

随机:14

随机数应介于:10 和 9 之间

随机:18

【问题讨论】:

  • 您的代码生成偏移量和偏移量+9 之间的数字。你需要像 10 + rand()%(offset - 11) 这样的东西。它会给你你想要的。无论如何,这是一个糟糕的代码。只需使用 C++11 随机生成器。
  • (rand() % 10) 产生一个从 0 到 9 的数字。所以 (rand() % 10) + offset 返回一个从 offset 到 offset+9 的数字

标签: c++ recursion random function-call


【解决方案1】:

(rand() % 10) 返回 [0, 9] 范围内的值,因此 (rand() % 10) + offset 将返回 [offset, offset + 9] 范围内的值。

如果您想返回 [offset, 10] 范围内的值,您需要 (rand() % (11 - offset)) + offset 以获取小于 11 的偏移量。

你也应该使用std::uniform_int_distribution 来获取范围内的随机整数。

【讨论】:

    【解决方案2】:

    (rand() % 10) 产生一个介于 0 和 9 之间的数字,然后您添加 offset 第一次 rand() % 10) 产生 6,您添加了 1。因此 7。第二次,rand() % 10) 的结果是 9,您在其中添加了 2,因此 11

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 2011-05-15
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      相关资源
      最近更新 更多