C:生成范围内随机数的数组(全部重复)

时间:2018-01-14 04:56:18

标签: c arrays random

我想写一个C函数,它得到:种子,int n(生成的随机整数的数量)和上限(允许的最大数量)。

我到目前为止有这样的事情:

// I need a function definition here
// I forgot how to allocate the int array ... somehting with 'sizeof'?
srand(time(NULL));   //seed for rand    
for(i = 0; i < length; i++)
        array[i] = rand()%upperLimit;
return array;

然后我可能需要这些头文件:

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

1 个答案:

答案 0 :(得分:-1)

#include <time.h>功能需要time。   这是一个简单的程序,可以将您的描述与代码中的注释相匹配:

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

int *
alocate (unsigned int n)
{
  return malloc (n * sizeof (int)); // allocate memory block for n numbers and return int pointer to it 
}

int *
generate_block_with_random_numbers (unsigned int n, int upper_limit)
{
//  function  `int *generate_block_with_random_numbers(unsigned int n, int upper_limit)` 
//  gets a positive integer n as an argument 
//  reserves the n block of int variables in memory 
//  fills this block with random values 
//  returns a pointer to the beginning of the reserved block. 

  srand (time (NULL));      //  seed generator

 int *array = alocate (n);  // note: array pointer always points to the beginning of the allocated memory  

  for (int i = 0; i < n; i++)
    {
      // you can index the array moving to its next element via [i] 
      array[i] = rand () % (upper_limit+1); // 
    }

  return array;
}


int
main ()
{

  unsigned int n = 5;
  unsigned int upperL = 5;

  int *block = generate_block_with_random_numbers (n, upperL);

  // Display the data contained in the returned block:
  for (int i = 0; i < n; i++)
    {
      printf ("%d\n", block[i]);    // print it
    }

  return 0;
}

输出:

5
0
2
3
3