为什么兰德每次都给我几乎相同(但略有不同)的数字

Why is rand giving me almost identical (but slightly different) numbers each time

本文关键字:数字 为什么      更新时间:2023-10-16

我写了以下一段代码来用 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;
}
相关文章: