为什么我不能将 rand() 与数组的大小一起使用?

Why can't I use rand() with the size of an array?

本文关键字:一起 数组 不能 rand 为什么      更新时间:2023-10-16

我正在尝试生成一个介于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;
}

你运行程序的每一秒都会得到一个新的随机数(因为你使用time()为伪随机数生成器种子(,但你不是在打印随机数,而是在打印motMystere的长度,所以更改

来自

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

cout << nombreRandom << endl;

请注意,由于C++11,不鼓励使用srand()rand()。使用新的<random>类和函数。

示例:

#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';
}

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

srand(time(0));
int nombreRandom = 0;
nombreRandom = rand() % tailleMotMystere;

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