【问题标题】:How can I get randomly generated numbers between 0 to 99 with 0 and 99 included? [duplicate]如何获得 0 到 99 之间的随机生成的数字,其中包括 0 和 99? [复制]
【发布时间】:2019-05-02 09:07:39
【问题描述】:

使用随机数函数随机生成0到99之间的10个整数,包括0到99

【问题讨论】:

  • 欢迎来到 Stack Overflow!如果您自己不进行任何研究,我们不会在这里为您做作业。但是,如果您展示自己尝试过的东西,例如通过发布minimal reproducible example 并在互联网上列出您研究过的网站,我们很高兴在最后几米上为您提供帮助。见meta.stackoverflow.com/questions/334822/…

标签: c++ random numbers generate


【解决方案1】:

这很简单。您需要使用标准的 srand/rand 函数。看这个例子:

#include <cstdlib>
#include <iostream>
#include <ctime>

int main() 
{
    // initialize random generator, by current time
    // so that each time you run - you'll get different values
    std::srand(std::time(nullptr)); 

    for(int i=0;i<10;i++)
    {
        // get rand number: 0..RAND_MAX, for example 12345
        // so you need to reduce range to 0..99
        // this is done by taking the remainder of the division by 100:
        int r = std::rand() % 100;

        // output value on console:
        std::cout << r << std::endl;
    }
}

这是使用 c++11 实现的现代变体。有些人更喜欢它:

#include <random>
#include <chrono>
#include <iostream>


int main()
{
    auto t = std::chrono::system_clock::now().time_since_epoch().count();
    std::minstd_rand gen(static_cast<unsigned int>(t));

    for(int i=0;i<10;i++)
        std::cout << gen() % 100 << std::endl;
}

【讨论】:

  • 好的,我的教授还没有教过我们这些,我们之前只使用过#include 并包含一个类。有没有办法以另一种方式生成随机数?除了循环,我不知道你代码的其他部分是什么意思。
  • 你需要读一些书,不要只依赖教授。我会注释一些你理解的代码。
  • 好吧,我研究了一下,我有点理解 srand 部分,但在视频中,我看到他们使用了 srand(time(0); std:: 有什么意义?为什么 nullptr?
  • std::time_t 时间(std::time_t* arg)。这个函数等待一个指针,而不是 int(0)。也许,该视频中有一种“老派技术”——基于 #define NULL 0#define NULL nullptr。你也可以写 std::srand(std::time(0));std::srand(std::time(NULL));
  • 这是非常过时的代码。
猜你喜欢
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 2012-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多