2014-12-30 155 views
0

随机数我有一个struct称为drug,我想为会员minimal_quantityquantity产生随机数。但每次运行代码时,我都会在这两个成员中得到相同的值,即所有生成的药物。生成成员结构

我的结构定义是这样的:

struct drug { 
    int code; 
    char name[25]; 
    int minimal_quantity; 
    int quantity; 
}; 

和产生药物的方法是这样的:

load_drugs_file(){ 
    int i; 

    for(i=0;i<=50;i++){ 

     if ((fp=fopen("drugs.dat","a+"))==NULL){ 
      printf("Error: impossible to open the file. \n"); 
      exit(1); 
     } 

    struct drug m; 
    srand(time(NULL)); 
    int r1 = rand() % 500; /* random int between 0 and 499 */ 
    int r2 = rand() % 1000; /* random int between 0 and 999 */ 

    m.code=i; 
    strcpy(m.name,"A"); 
    m.minimal_quantity=r1; 
    m.quantity=r2; 

    fwrite(&m,sizeof(m),1,fp); 

    fclose(fp); 
    } 
} 

有什么建议?

+2

你可以显示你得到的输出吗?另外,我强烈建议将循环的'fopen'和'fclose' ** ** **。没有理由继续打开和关闭文件。 – dg99

+0

为什么不是在该函数的名称之前指定的返回类型? –

+0

你怎么知道你总是得到相同的两个“随机”数字? –

回答

1

移动srand(time(NULL));main()

如果你在很短的时间间隔内调用它,随机种子总是相同的,这就是为什么你得到相同的价值。

如果您在main()函数中调用它,则每次后续调用rand()都会给出不同的值,并且每次运行程序时,种子都会有所不同。

+0

非常感谢! – MrPedru22