【问题标题】:My function for generating random numbers isn't going past 500000我生成随机数的函数不会超过 500000
【发布时间】:2021-02-13 01:12:38
【问题描述】:

我会直接解决我的问题。所以基本上我想做的是生成一个不同数量的随机数数组。所以一个有 10,000、50,000、100,000、500,000、600,000 等。然后我会使用快速排序对它们进行排序并将排序后的数组打印到屏幕上。此外,它的运行时间也将被记录和打印。然而,我唯一遇到的问题是生成数组。由于某种原因,生成过去 500,000 个随机数不起作用并返回:


进程在 2.112 秒后退出,返回值 3221225725

按任意键继续。 . . ([1]:https://i.stack.imgur.com/m83el.png)

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void randNums(int array[], int range) {
    int i, num;
    for (i = 0; i < range; i++) {
        num = rand() % range;
        array[i] = num;
    }
}

//prints elements of given array
void display(int array[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        printf("#%d. %d\n", i, array[i]);
    }
}

//displays time taken for sorting algorithm to run
void timeTaken(char sortingAlgo[], int size, clock_t start, clock_t end) {
    double seconds = end - start;
    double milliseconds = seconds / 1000;
    printf("Time taken for %s Sort to sort %d numbers was %f milliseconds or %f seconds",
           sortingAlgo, size, milliseconds, seconds);       
}
 
//quick sort
void quickSort(int array[], int first, int last) {
    int i, j, pivot, temp;
    if (first < last) {
        pivot = first;
        i = first;
        j = last;
        while (i < j) {
            while (array[i] <= array[pivot] && i < last)
                i++;
            while (array[j] > array[pivot])
                j--;
            if (i < j) {
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
        temp = array[pivot];
        array[pivot] = array[j];
        array[j] = temp;
        quickSort(array, first, j - 1);
        quickSort(array, j + 1, last);
    }
}

int main() { 
    int size = 600000;
    int myArray[size];
    time_t end, start;
    int first, last;

    randNums(myArray, size);    
    first = myArray[0];
    last = sizeof(myArray) / sizeof(myArray[0]);
    
    time(&start);
    quickSort(myArray, first, last);
    time(&end); 
    display(myArray, size);
    timeTaken("Quick", size, start, end);

    return 0;
}

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 你的RAND_MAX是什么?
  • 您的堆栈大小有限,大数组会导致问题。如果您使用任何大小不一的东西,请使用 calloc()malloc()
  • 哦,哇,好吧,我在想这个,但我不想让事情变得过于复杂,而且我对内存分配真的不是很好。谢谢!另外,我不确定 RAND_MAX 的事情。
  • 我只提到RAND_MAX,因为在某些系统上它真的很微不足道,32767 或更少,这意味着对于大型数组,您将有很多重复的值。始终注意堆栈限制。大约 1000 件物品很好,但除此之外,您就会开始进入危险区域。请记住,堆栈是为整个程序准备的,因此您需要避免将重物放入其中。
  • OHHHH 好的,明白了。谢谢。抱歉,我对 C 及其复杂性还是有点陌生​​。我在 malloc() 上查找了更多信息并试了一下。我很高兴地说它可以很好地生成我需要的整数数量。但是,现在我的快速排序功能无法使用它,这与以前不同。

标签: arrays c random data-structures numbers


【解决方案1】:

这段代码中有很多小错误,解决起来并不难。我将尝试在此重构和清理中对其进行分解:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void randNums(int* array, int range) {
  // Declare iterator variables like `i` within the scope of the iterator.
  for (int i = 0; i < range; i++) {
    // No need for a single-use variable here, just assign directly.
    array[i] = rand () % range;
  }
}

void display(int* array, int size) {
  // for is not a function, it's a control flow mechanism, so
  // it is expressed as `for (...)` with a space. `for()` implies
  // it is a function, which it isn't.
  for (int i = 0; i < size; i++) {
    printf("#%d. %d\n", i, array[i]);
  }
}

void timeTaken(char* sortingAlgo, int size, clock_t start, clock_t end) {
  // Time calculation here needs to account for the fact that clock_t
  // does not use seconds as units, it must be converted
  // https://en.cppreference.com/w/c/chrono/clock_t

  printf(
    "Time taken for %s Sort to sort %d numbers was %.6f seconds",
    sortingAlgo,
    size,
    ((double) (end - start)) / CLOCKS_PER_SEC
  );
}

void quickSort(int* array, int first, int last) {
   // Establish a guard condition. Rest of the function is no longer
   // nested in a control flow structure, so it simplifies the code.
   if (first >= last) {
     return;
   }

  int pivot = first;
  int i = first;
  int j = last;

  // Use `while (...)` as it's also a control flow structure.
  while (i < j) {
    // Adding space around operators improves clarity considerably. Unspaced
    // elements like `a->b()` are supposed to stand out and not be confused
    // with visually similar `a>>b()` which does something very different.
    while (array[i] <= array[pivot] && i < last) {
      i++;
    }

    // Use surrounding braces on all blocks, even single-line ones, as this
    // can avoid a whole class of errors caused by flawed assumptions.
    // while (...) { ... }
    while (array[j] > array[pivot]) {
      j--;
    }

    if (i < j) {
      int temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
  }

  int temp = array[pivot];
  array[pivot] = array[j];
  array[j] = temp;

  quickSort(array, first, j - 1);
  quickSort(array, j + 1, last);
}

int main(int argc, char** argv) {
  int size = 600000;

  // If an argument was given...
  if (argc > 1) {
    // ...use that as the size parameter instead.
    size = atol(argv[1]);
  }

   // Allocate an array of sufficient size
  int* numbers = calloc(size, sizeof(int));

  randNums(numbers, size);

  // time_t has at best second-level precision, it's very inaccurate.
  // Use clock_t which gives far more fidelity.
  clock_t start = clock();

  // This function takes *offsets*, not values.
  quickSort(numbers, 0, size - 1);

  clock_t end = clock();

  display(numbers, size);

  timeTaken("Quick", size, start, end);

  free(numbers);

  return 0;
}

这里的第一个错误是错误地调用quickSort()

// Represents first *value* in the array
first = myArray[0]; // Should be: 0

// Rough calculation of the size of the array, but this is off by one
last = sizeof(myArray)/sizeof(myArray[0]); // Should be: size - 1
    
quickSort(myArray, first, last);

【讨论】:

  • 哇。非常感谢你。这确实解决了我最初的问题和我之后遇到的其他问题,并且包括了很多我真的不知道的东西。感谢您的帮助、时间和洞察力,我将通过更多的学习和实践来充分利用它。
猜你喜欢
  • 2016-10-08
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 2015-12-20
  • 2016-06-12
  • 1970-01-01
相关资源
最近更新 更多