我编写了下面的代码来生成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 ("%d\n", 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。
发布于 2020-02-11 18:16:38
问题是MAX_VAL被定义为ARRAY_SIZE*5+1,而不是(ARRAY_SIZE*5+1)。这意味着您在arr[i] = (rand() % MAX_VAL);中的使用扩展到:
arr[i] = (rand() % 5 * 5 + 1);没有太多的选择(只有5种可能性),这就是为什么你看到相同的数字。您可以通过插入MAX_VAL的定义或使其成为内容变量来修复此问题:
const unsigned int MAX_VAL = ARRAY_SIZE * 5 + 1;第二个问题是srand(time(NULL))的使用。在大多数系统上,如果程序在同一秒钟内运行,time将返回相同的值。这意味着快速连续运行程序(在同一秒钟内)将产生相同的结果。最好使用中的PRNG设施。
发布于 2020-02-11 18:20:19
这是因为您使用了#define MAX_VAL
实际的计算是rand() % 5 * 5 + 1,这意味着首先用5对rand()结果进行模块化,然后乘以5,然后再添加1。
我假设您的意思是编写可以通过以下方法解决的rand () % (5 * 5 + 1):
#define MAX_VAL (ARRAY_SIZE * 5 + 1)发布于 2020-02-11 18:29:56
其他人已经指出了这段代码中的两个主要问题,但值得在这里展示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;
}https://stackoverflow.com/questions/60175064
复制相似问题