[英]Rand() is generator the same number even though I called srand(time(NULL))
Here is my code 这是我的代码
#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;
}
For some reason, it keeps giving me 100 when I generate the random number. 由于某种原因,当我生成随机数时,它会一直给我100。 Though I don't believe it should because I called srand(time(NULL)) to initialize a seed. 虽然我不相信这应该是因为我调用srand(time(NULL))来初始化种子。
As said in the comments, rand() % 1
is nonsensical. 如评论中所述, rand() % 1
是荒谬的。 The remainder of anything divided by 1 is 0. You then add 100 to it. 除以1的余数为0。然后将其加100。
Instead, (rand() % 100) + 1
will give you a random number in the range [1, 100]. 而是(rand() % 100) + 1
将为您提供[1,100]范围内的随机数。
The facilities in <random>
are much better, and it is a good idea to learn them. <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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.