【发布时间】:2020-10-29 10:17:03
【问题描述】:
程序的目标是生成一个介于 1 和 N 之间的随机数字序列,其中 N 作为参数传递给程序,并将生成的序列写入文件。
我的文件没有生成。我究竟做错了什么?我的代码中是否有任何错误?我的代码有问题吗?我输出的文件是否正确?
/*01*/ //
/*02*/ // random_sequence_v6.c
/*03*/ // Generate a random sequence of all numbers between 1 to N
/*04*/ //
/*05*/ #include "stdio.h"
/*06*/ #include "stdint.h"
/*07*/ #include "stdlib.h"
/*08*/ #include "stdint.h"
/*09*/ #include "sys/types.h"
/*10*/ #include "sys/stat.h"
/*11*/ #include "fcntl.h"
/*12*/ #include "assert.h"
/*13*/ #include "inttypes.h"
/*14*/
/*15*/ typedef uint64_t value_t;
/*16*/
/*17*/ value_t* generate_sequence(int num_values)
/*18*/ {
/*19*/ assert(num_values > 0);
/*20*/ value_t* data = calloc(num_values, sizeof(int));
/*21*/ for (int i = 0; i <= num_values; i++) {
/*22*/ data[i] = i;
/*23*/ }
/*24*/ return data;
/*25*/ }
/*26*/
/*27*/ int random_value(int min, int max)
/*28*/ {
/*29*/ int random_number;
/*30*/ do {
/*31*/ random_number = rand();
/*32*/ } while ((random_number <= min) || (random_number >= max));
return random_number;
/*33*/ }
/*34*/
/*35*/ void randomize_sequence(value_t* sequence, int num_values)
/*36*/ {
/*37*/ // Fisher-Yates
/*38*/ for(int i = 0; i < num_values-2; i++) {
/*39*/ int random_index = random_value(i, num_values-1);
/*40*/ // Swap them
int temp = sequence[i];
/*41*/ sequence[i] = sequence[random_index];
/*42*/ sequence[random_index] = temp;
/*43*/ }
/*44*/ }
/*45*/
/*46*/ int main(int argc, char* argv[])
/*47*/ {
/*48*/ int num_values = strtoul(argv[1], NULL, 10);
/*49*/ value_t* pValues = generate_sequence(num_values);
/*50*/
/*51*/ randomize_sequence(pValues, num_values);
/*52*/
/*53*/ // Record results
/*54*/ FILE *fd = fopen("results.txt", "w+");
/*55*/ for (int i = 0; i < num_values; i++) {
/*56*/ fprintf("%i = %"PRIu64"\n", i, pValues[i]);
/*57*/ }
/*58*/ fclose(fd);
/*59*/
/*60*/ return EXIT_SUCCESS;
/*71*/ }
【问题讨论】:
-
for (int i = 0; i <= num_values; i++)应该是<和random_value()可能需要很长时间。 -
分配错误。
value_t* data = calloc(num_values, sizeof(int));-->value_t* data = calloc(num_values, sizeof *data); -
fprintf("%i = %"PRIu64"\n", i, pValues[i]);-->fprintf(fd,"%i = %"PRIu64"\n", i, pValues[i]); -
您也可以用
random_number = (rand() % (max - min + 1)) + min ;替换整个do while循环......每次都会保证您的值在您的范围内。它会让它更快。在网上找到的