【问题标题】:Why can't I use rand() with the size of an array?为什么我不能将 rand() 与数组的大小一起使用?
【发布时间】:2020-07-12 07:10:10
【问题描述】:

我正在尝试生成一个介于 0 和数组大小之间的数字。 有我的代码,但输出始终为 2。 编辑:我尝试使用另一个编译器,输出只有 7 请帮帮我。

这是我的完整代码

#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <string>
#include <ctime>

using namespace std;
int main (){

    string motMystere = ("Bonjour");
    int tailleMotMystere (0);
    vector<string> motMelange;
    tailleMotMystere= motMystere.size();
    srand(time(0));
    int nombreRandom = 0;
    
    nombreRandom = rand() % tailleMotMystere;
    cout << motMystere.size() << endl;
    return 0;
}

【问题讨论】:

  • 即使这个数字链也可以是随机的:2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 ,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2。也许你只是运气不好
  • 因为它被标记为 C++,我建议你考虑使用 C++ random features
  • 您是否在每次拨打rand 之前都拨打srand?我不知道,因为这不是minimal reproducible example。如果你是,你不应该。
  • @c_kusanagi 能否请您提供整个代码(如果您正在循环并调用 rand(),请也包括在内。)
  • 根据您提供的代码,您不应该得到重复的结果。但是,如果您将它们放入某种循环中,则可能是您的循环结构错误。

标签: c++ arrays random


【解决方案1】:

您将在运行程序的每一秒获得一个新的随机数(因为您使用time() 为伪随机数生成器提供种子),但您没有打印随机数,您正在打印@987654323 的长度@,所以改变

来自

cout << motMystere.size() << endl;

cout << nombreRandom << endl;

请注意,自 C++11 起不鼓励使用 srand()rand()。使用新的&lt;random&gt; 类和函数。

例子:

#include <cstddef>
#include <iostream>
#include <random>
#include <string>

int main (){
    std::mt19937 prng(std::random_device{}()); // A seeded PRNG

    std::string motMystere  = "Bonjour";
    size_t tailleMotMystere = motMystere.size();
    
    // Distribution: [0, tailleMotMystere)
    std::uniform_int_distribution<size_t> dist(0, tailleMotMystere - 1);
    
    size_t nombreRandom = dist(prng);
    std::cout << nombreRandom << '\n';
}

【讨论】:

  • 我一遍又一遍地做同样的事情,却得到同样的结果——怎么了?
【解决方案2】:

错误是你在调用rand()之前每次都调用srand

srand(time(0));
int nombreRandom = 0;

nombreRandom = rand() % tailleMotMystere;

您应该在程序开始时调用srand一次

【讨论】:

  • @john 小澄清,OP 只调用了一次 rand() 函数,那么你问这个" every time before you call rand() " 的意图是什么?
  • @SaiSreenivas 问题和代码暗示 OP 有某种包含已发布代码的循环。如果他们不这样做,他们就不会问这个问题。
猜你喜欢
  • 1970-01-01
  • 2020-08-26
  • 2013-07-02
  • 2015-11-08
  • 2013-08-24
  • 1970-01-01
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多