<分区>
我有以下工作正常的代码:
#include <stdio.h>
#include <stdlib.h>/*need this for rand()*/
#include "random.h"
#include <time.h>/*for time() function*/
int main()
{
int arr[5], a = 0;
printf("enter 5 array elements\n");
scanf("%d", &arr[0]);
scanf("%d", &arr[1]);
scanf("%d", &arr[2]);
scanf("%d", &arr[3]);
scanf("%d", &arr[4]); /*scan all elements*/
srand(time(NULL)); /*set the seed*/
a = arr[rand() % ARR_SIZE(arr)];/*from .h file*/
printf("%d\n",a);/*print the random element generated above*/
return 0;
}
它为 5 个整数的数组选择一个随机整数。
我需要对其进行以下修改:
一个函数应该接受两个参数——一个空指针数组和数组长度。它应该返回一个空指针。
该函数应从数组中随机选择一个元素并将其返回。
int main() 必须为随机数生成器提供种子,然后调用该函数。最后它应该打印生成的随机元素。
我不知道如何修改它以满足上述要求。
这里是 random.h 文件的内容:
#define ARR_SIZE(arr) ( sizeof((arr)) / sizeof((arr[0])) )