【问题标题】:Generate random number for member in struct为结构中的成员生成随机数
【发布时间】:2015-02-26 19:28:46
【问题描述】:

我有一个名为drugstruct,我想为成员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); 
    }
}

有什么建议吗?

【问题讨论】:

  • 你能显示你得到的输出吗?另外,我强烈建议将fopenfclose out 退出循环。没有理由继续打开和关闭文件。
  • 为什么没有在函数名前指定返回类型?
  • 你怎么知道你总是得到相同的两个“随机”数字?

标签: c random struct


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2013-06-16
    • 2022-08-11
    • 2017-05-20
    • 1970-01-01
    相关资源
    最近更新 更多