【问题标题】:Rand() is generator the same number even though I called srand(time(NULL))Rand() 生成相同的数字,即使我调用了 srand(time(NULL))
【发布时间】:2016-05-30 03:50:06
【问题描述】:

这是我的代码

#include <iostream> //cout, cin
#include <time.h> // time
#include <stdlib.h> // srand(), rand()
using std::cout; //cout

int main()
{
    srand(time(NULL)); //Initializes a random seed
    int rand_number = rand() % 1 + 100; //Picks a random number between 1 and 100

    cout << rand_number << std::endl;
}

由于某种原因,当我生成随机数时它一直给我 100。虽然我不相信它应该因为我调用 srand(time(NULL)) 来初始化种子。

【问题讨论】:

  • rand() % 1 将永远是0

标签: c++ random numbers generator srand


【解决方案1】:

正如 cmets 中所说,rand() % 1 是荒谬的。任何东西除以 1 的余数是 0。然后你再加上 100。

相反,(rand() % 100) + 1 会为您提供 [1, 100] 范围内的随机数。

&lt;random&gt;的设施要好很多,学习一下是个好主意。

std::mt19937 mt((std::random_device()())); //create engine
std::uniform_int_distribution<int> dist(1, 100); //define distribution

dist(mt); //better random number in range [1, 100]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多