为什么我不能将 rand() 与数组的大小一起使用?
Why can't I use rand() with the size of an array?
我正在尝试生成一个介于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
一次。
相关文章:
- 为什么我不能将 rand() 与数组的大小一起使用?
- 在将 new 与指针一起使用时,创建数组的指定长度
- 为什么我们将 [ ] 与指向数组的指针一起使用?
- 如何将数组与指针一起使用?
- 如何将 std::find() 与 2d std: 数组一起使用?
- 程序在初始化期间未与数组一起运行
- 将 find_if() 与数组一起使用的代码段中出错
- C 排序无法解析标识符开始和结束吗?(将数组保持在一起)
- 如何将单独的数组分组在一起(类似于按一列对表进行排序)
- 是否可以将isdigit,isalpha函数与输入的字符串数组一起使用
- 如何加入两个指针以将其串在一起并将其存储在数组或字符中
- 如何将初始值设定项与右值引用参数一起使用 // 为什么不能使用另一个 C 样式数组变量初始化 C 样式数组
- 将MPI_Scatter与 char* 数组一起使用
- 在模板参数中使用 auto:一些使用示例和..如何使其与恒定大小的 C 数组一起使用
- 将模板气泡排序与结构数组一起使用时出现问题
- 将'sort'与字符数组一起使用 (C++)
- Strncpy只能与固定长度的数组一起使用
- 有可能实现一个与数组而不是单个对象一起工作的内存池吗
- 将字符数组连接在一起
- 要与MKL一起使用的数组类型