简体   繁体   English

即使我叫srand(time(NULL)),Rand()还是生成器相同的数字

[英]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.

相关问题 rand()生成相同的数字 - 即使我的主要是srand(time(NULL))! - rand() generating the same number – even with srand(time(NULL)) in my main! 通过函子调用时,rand()会生成相同的随机数集(即使在使用srand(time(NULL))进行播种之后) - rand() generating same set of random numbers when called through functors (even after seeding with srand(time(NULL)) rand()即使与srand(time(NULL))也不起作用 - rand() doesn't work even with srand( time(NULL) ) rand() 即使在 srand(time(NULL)) 之后也不生成随机数 - rand() not generating random numbers even after srand(time(NULL)) 即使srand(time(0))调用一次,std :: random_shuffle也会产生相同的结果 - std::random_shuffle produce the same result even though srand(time(0)) called once 创建一个随机数生成器srand和rand undefined - Creating a Random Number Generator srand and rand undefined 为什么即使反复重置srand(time(NULL))仍能正常工作? - Why is srand(time(NULL)) working smoothly even though I repeatedly reset it? rand()即使在srand()之后也产生相同的结果 - rand() producing the same results even after srand() Srand() 和 rand() 仍然生成相同的随机数 - Srand() and rand() still generating the same random number 为什么rand()在这个for循环中使用srand(time(null))返回相同的值? - Why does rand() return the same value using srand(time(null)) in this for loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM