【问题标题】:srand() is not working when used with non-constant parametersrand() 与非常量参数一起使用时不起作用
【发布时间】:2021-11-02 15:58:04
【问题描述】:

srand() 有问题。它仅在我使用数字作为参数时有效,例如 srand(1234),但当我尝试将其与 'n' 或 time 一起使用时(如下所示),randint() 会一直返回相同的值。

#include <iostream>
#include <experimental/random>
#include <cstdlib>
#include <ctime>

using namespace std;

int main() {
    srand(time(nullptr));
    for (int i = 0; i < 4; ++i) {
        int random = experimental::randint(0, 9);
        cout << random;
    }
}

感谢您的宝贵时间。

【问题讨论】:

  • 我不认为srandexperimental::randint 有任何联系。
  • Works here。我也赞同这一点,randint 的部分观点是您不必处理srand
  • @MarkRansom 那么为什么我在运行前填写数字时它运行良好。
  • 这是实验性的。检查您的实现对randint 的支持。你大概可以直接看到它的源代码。
  • 你试过reseed()吗?

标签: c++ random srand c++-experimental


【解决方案1】:

C 函数srand 旨在与C 函数rand 结合使用。这些是与 C++ 的 std::experimental 标头中的函数不同的函数。后者中的 randint 函数旨在与同一标头中的 reseed 函数一起使用:

#include <experimental/random>
#include <iostream>

int main() {
    std::experimental::reseed();

    for (int i = 4; i--; ) {
        int random = std::experimental::randint(0, 9);
        std::cout << random << '\n';
    }
}

但是,这里没有必要使用实验性功能。从C++11开始就有std::uniform_int_distribution

#include <iostream>
#include <random>
 
int main() {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distrib(0, 9); // Default type is 'int'
 
    for (int i = 4; i--; ) {
        int random = distrib(gen);
        std::cout  << random << '\n';
    }
}

此方法比 C 标准库中的方法更灵活,通常应在 C++ 中首选。

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    相关资源
    最近更新 更多