gpt4 book ai didi

c++ - srand() 正在输出错误的值

转载 作者:行者123 更新时间:2023-11-28 04:32:26 25 4
gpt4 key购买 nike

所以我正在制作一个选择排序程序,我必须在其中输入两个值:一个用于数组中使用的数字,另一个用于随机数生成器的种子。我对如何调整使用的数量有点困惑,因为我们可以放入的最大元素数量是 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)时,它输出

UNSORTED: 25 36 35 24 24 34 38 22 29 29

SORTED: 22 24 24 25 29 29 34 35 36 38

什么时候输出

UNSORTED: 28 28 34 37 36 27 33 36 36 39

SORTED: 27 28 28 33 34 36 36 36 37 39

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

最佳答案

这段代码有很多话要说:

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

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

关于c++ - srand() 正在输出错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52510340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com