【问题标题】:srand() is outputting the wrong valuessrand() 输出错误的值
【发布时间】:2018-09-26 05:12:06
【问题描述】:

所以我正在制作一个选择排序程序,其中我必须输入两个值:一个用于数组中使用的数字,另一个用于随机数生成器的种子。我只是对如何调整使用的数字有点困惑,因为我们最多可以放入 15 个元素。数组目前有 8 个。每个元素应该是 20 到 40 之间的数字。

#include <iostream>
using namespace std;

int selectionSort(int[], int);

int selectionSort(int numbers[], int numbersSize) {
int i = 0;
int j = 0;
int indexSmallest = 0;
int temp = 0;  // Temporary variable for swap

for (i = 0; i < numbersSize - 1; ++i) {

// Find index of smallest remaining element
indexSmallest = i;
for (j = i + 1; j < numbersSize; ++j) {

if (numbers[j] < numbers[indexSmallest]) {
indexSmallest = j;
}
}

// Swap numbers[i] and numbers[indexSmallest]
temp = numbers[i];
numbers[i] = numbers[indexSmallest];
numbers[indexSmallest] = temp;
}
return indexSmallest;
}

int main() {
int numbers[] = {10, 2, 78, 4, 45, 32, 7, 11, 0, 0, 0, 0, 0, 0, 0};
const int NUMBERS_SIZE = 15;
int i = 0;
int nums = 0;
int seed = 0;

cin >> nums;
cin >> seed;

srand(seed);

for (int i = 0; i < nums; i++) {
numbers[i] = (rand() % 20) + 20;
}

cout << "UNSORTED: ";
for (i = 0; i < nums; ++i) {
cout << numbers[i] << " ";
}
cout << endl;

selectionSort(numbers, nums);

cout << "SORTED: ";
for (i = 0; i < nums; ++i) {
cout << numbers[i] << " ";
}
cout << endl;

system("pause");
return 0;
}

唯一的问题是生成的随机数是错误的数字。例如,当我输入“10 100”(数组中使用的数字为 10,种子为 100)时,它会输出

未分类:25 36 35 24 24 34 38 22 29 29

排序:22 24 24 25 29 29 34 35 36 38

什么时候输出

未分类:28 28 34 37 36 27 33 36 36 39

排序:27 28 28 33 34 36 36 36 37 39

我不确定如何解决这个问题。

【问题讨论】:

标签: c++


【解决方案1】:

关于这段代码有很多话要说:

  • 放入数组numbers[]的初始值当然会被覆盖。
  • NUMBERS_SIZE 未使用。
  • 如果您希望能够指定数组长度作为输入参数,您应该使用std::vector&lt;&gt;,或者动态创建数组,或者至少检查给定值的数量不超过数组大小。
  • rand() 是一个随机数生成器,srand() 为这些随机数设置某种种子。保证使用相同的种子,您将始终获得相同的随机数序列。
    但是,您为什么/如何期望知道将生成的数字?
  • 缩进。
  • 不要做using namespace std;

您的问题的答案是:不要使用随机数。

【讨论】:

  • 我不得不这样做。我的说明说“第二个输入应该是随机数生成器的种子。”
  • 另见:stackoverflow.com/questions/28374800/…stackoverflow.com/questions/3503825/… 简而言之:如果您在相同的环境中使用相同的种子(即相同的机器,相同的库在相同的执行周期),您将拥有相同的序列。因此,预计您在不同的环境中会有不同的序列。
  • @JohnSmith 这没有错,但是你不能指望得到特定的值!
  • @Ilya 感谢您的澄清。我默默地假设 OP 总是在同一个环境中运行程序。
【解决方案2】:

你可以试试 rand 函数

/* initialize random seed: */ srand (time(NULL)); /* generate random number betwee 1 and 10: */ iSecret = rand() % 10 + 1;

你还需要包含 3 个库

#include &lt;stdio.h&gt; /* printf, scanf, puts, NULL */

#include &lt;stdlib.h&gt; /* srand, rand */

#include &lt;time.h&gt; /* time */

【讨论】:

  • 复制文档如何回答这个问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-07
  • 2011-09-20
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多