我想写一个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>
答案 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