c - 在 C89 中打印随机数组元素

标签 c random c89

<分区>

我有以下工作正常的代码:

#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])) )

最佳答案

这应该可以解决问题。

void* getRandomElement(void** array, int size)
{
    int* arr = (int*)*array;
    return (void*)&(arr[rand() % size]);
}

int main(void)
{
    int arr[5];
    void* p = (void*)arr;
    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*/
    printf("random element %d\n", *(int*)getRandomElement(&p, ARR_SIZE(arr)));
    return 0;
}

关于c - 在 C89 中打印随机数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52892806/

相关文章:

c# - 重复获取相同的随机数

c# - .Net 的 `Random` 类中的错误?

c# - 如何让 AutoFixture 创建一个 >0 的整数,而不是另一个数字?

c - K&R 练习 1.16 - 线长限制

c - 返回无值

客户端服务器 tcp/ip 聊天室应用程序

c - while循环不起作用?

c - 结构类型转换 ANSI C 89

无法访问子进程中创建的共享内存

c - 函数导致通过引用传递的变量出现意外行为