Rand()是生成器相同的数字,即使我调用了srand(time(NULL))

时间:2016-02-18 05:39:11

标签: c++ random numbers generator srand

这是我的代码

#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))来初始化种子。

1 个答案:

答案 0 :(得分:3)

如评论中所述,rand() % 1是荒谬的。除以1的余数为0.然后将其加100。

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

<random>中的设施要好得多,学习它们是个好主意。

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]
相关问题