首页 > 解决方案 > How can i pick a number from an array in C?

问题描述

Basically i made an array with number 1,2,3.

int array[3] = {1,2,3};

How can I select a random number from this list and assign it to a different variable?

标签: c

解决方案


Use the rand() function and mod the result down to 3 values 0, 1, or 2 using mod. Then access the corresponding value in your array:

    srand(time(NULL));//  without this rand() function might continuously give the same value
    int index = rand() % 3;
    printf("random: %d\n", array[index]);

Considering that the array contains hardcoded values, you could simply:

int i = (rand() % 3) + 1;
printf("random: %d\m", i);

Include the header file <stdio.h>, <time.h>, <stdlib.h>


推荐阅读