结构C中给定数字的随机数

时间:2015-02-06 22:02:39

标签: c pointers structure

我的结构设置如下

struct judges
{
    char surname[20];
    int id;
    struct judges *wsk;
}

如何从给定ID中获取随机数?例如,我添加3个ID为3,7和253的评委,是否有办法从这些中获取随机数?

4 个答案:

答案 0 :(得分:2)

从这些结构的数组中选择一个随机项并读取其ID。

答案 1 :(得分:1)

您可以使用srand()设置随机种子(在本例中为ID),然后使用rand()获取每位裁判的随机数。您也可以使用[Glib随机数(https://developer.gnome.org/glib/2.42/glib-Random-Numbers.html)代替标准C函数。

答案 2 :(得分:1)

是的,从数组中选择一个随机数 但要在阵列中选择一个,您必须使用:

rand() % arrayLength;
//in your case:
rand() % 3; //returns 0,1,or 2`

答案 3 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

main(){
       struct judges judge;
       int index,i;
       time_t t;
       srand((unsigned int)time(&t));

       int ids[]={3,7,253};
       index=rand() % 3;
       judge.id=ids[index];
}

您需要构建一个id数组,然后使用srand()和rand()生成一个随机索引,并将其分配给judge.id字段。


如果您想了解有关生成http://www.tutorialspoint.com/c_standard_library/c_function_rand.htm的随机数的更多信息 http://www.tutorialspoint.com/c_standard_library/c_function_srand.htm