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

问题描述:

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

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.

示例代码

取数组

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 将接收一个介于 013
之间的值最后

i will receive a value between 0 to 13
At last

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