为什么兰德每次都给我几乎相同(但略有不同)的数字
Why is rand giving me almost identical (but slightly different) numbers each time
我写了以下一段代码来用 c++ 生成随机数
#include <stdlib.h>
#include <iostream>
#include <ctime>
#define ARRAY_SIZE 5
#define MAX_VAL ARRAY_SIZE*5+1
int main() {
srand(time(NULL));
int arr [ARRAY_SIZE];
for (int i = 0; i < ARRAY_SIZE; i++) {
arr[i] = (rand() % MAX_VAL);
}
for (int i = 0; i < ARRAY_SIZE; i++) {
printf ("%dn", arr[i]);
}
return 0;
}
当我运行这个时,我每次都会得到几乎相同的数字:
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
11
16
16
21
16
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
21
11
21
11
6
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
6
6
1
16
6
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
16
1
16
6
21
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
1
21
21
11
21
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
1
21
21
11
21
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
11
16
1
1
11
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
11
16
1
1
11
tyler@Tylers-MacBook-Pro hw2 % ./MergeSort
21
1
6
6
1
为什么我的随机数生成器只给我值:1、6、11、16 和 21? 这对我来说毫无意义。 我确保播种它,数字并不总是以相同的顺序,这使得这更加令人困惑。 作为旁注,我正在使用OSX。
问题是MAX_VAL
被定义为ARRAY_SIZE*5+1
,而不是(ARRAY_SIZE*5+1)
。这意味着您在arr[i] = (rand() % MAX_VAL);
中的用途将扩展到:
arr[i] = (rand() % 5 * 5 + 1);
没有很多选择(只有 5 种可能性(,这就是为什么您看到相同的数字。您可以通过将MAX_VAL
的定义括起来或使其成为 contant 变量来解决此问题:
const unsigned int MAX_VAL = ARRAY_SIZE * 5 + 1;
次要问题是使用srand(time(NULL))
.在大多数系统上,如果程序在同一秒内运行,time
将返回相同的值。这意味着快速连续运行程序(在同一秒内(将产生相同的结果。最好在<random>
使用PRNG设施。
这是因为您使用了#define MAX_VAL
实际计算是rand() % 5 * 5 + 1
,这意味着,您首先将 rand(( 结果取模为 5,然后乘以 5,然后加 1。
我假设你的意思是写rand () % (5 * 5 + 1)
这可以通过以下方式解决:
#define MAX_VAL (ARRAY_SIZE * 5 + 1)
其他人已经指出了这段代码中的两个主要问题,但值得在这里展示C++做事的方式,以形成对比,并取消学习许多首先破坏这段代码的 C 思维。
此代码的C++版本通过使用C++具有而 C 缺少的功能来回避这里的许多问题:
#include <random>
#include <vector>
#include <iostream>
int main() {
// Define constants instead of using #define, as this avoids interpolation syntax issues
const size_t array_size = 5;
const int max = array_size * 5 + 1;
// Use the C++ random number generator facilities
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, max);
// Use a dynamically sized array
std::vector<int> arr;
for (int i = 0; i < array_size; ++i) {
arr.push_back(dis(gen));
}
// Use C++ container iteration to simplify code
for (const int& i : arr) {
// Use streams for output
std::cout << i << std::endl;
}
return 0;
}
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 为什么兰德每次都给我几乎相同(但略有不同)的数字
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 为什么当我输入较大的数字时,我的程序会到达文件末尾?
- 为什么使用数组元素查找最大数字的程序不起作用?
- C++ 为什么数字限制不适用于uint8_t和int8_t?
- 为什么strlen(s)与s的大小不同,为什么cout-char显示的是字符而不是数字
- 为什么我C++得到这个随机的奇怪数字
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- 为什么我的位移给出不正确的数字
- 为什么 sf::Text 显示点而不是数字?
- 反转一个数字程序不起作用,为什么?
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 为什么当我输入一个大数字时,输出会一遍又一遍地重复?
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作
- 为什么我的 while 循环永远不会在 C++ 中的数字猜测游戏中结束?
- 为什么当我在 c++ 中运行函数时,我的代码显示数字 53