如何从一组数字(不是范围)生成随机数

时间:2022-01-01 20:33:02

I would like to be able to generate a random number from a group of numbers, like for example: 1, 2, 3, 12, 11, 23, 45, 54, 10, 10, 12, 23, 35, 24. Using the rand and the srand i can generate random numbers different each time but i would like to able to condition the outcomes by generating random numbers from a group.

我希望能够从一组数字中生成一个随机数,例如:1,2,3,12,11,23,45,54,10,10,12,23,35,24。 rand和srand我可以每次产生不同的随机数,但我希望能够通过从一个组中生成随机数来调节结果。

1 个解决方案

#1


3  

Example code

Take an Array

拿一个数组

int a[]={ 1, 2, 3, 12, 11, 23, 45, 54, 10, 10, 12, 23, 35, 24};
int i = rand()%14; // here 14 is number of element in array.

i will receive a value between 0 to 13
At last

我将收到0到13之间的值

printf("%d",a[i]);    //print that array index

#1


3  

Example code

Take an Array

拿一个数组

int a[]={ 1, 2, 3, 12, 11, 23, 45, 54, 10, 10, 12, 23, 35, 24};
int i = rand()%14; // here 14 is number of element in array.

i will receive a value between 0 to 13
At last

我将收到0到13之间的值

printf("%d",a[i]);    //print that array index