How can I generate a random number from a group of numbers (not a range)

╄→гoц情女王★ 提交于 2020-01-05 02:52:13

问题


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:


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

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


来源:https://stackoverflow.com/questions/26927978/how-can-i-generate-a-random-number-from-a-group-of-numbers-not-a-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!