【发布时间】:2015-02-26 19:28:46
【问题描述】:
我有一个名为drug 的struct,我想为成员minimal_quantity 和quantity 生成随机数。但是每次我运行代码时,对于生成的所有药物,我都会在这两个成员中得到相同的值。
我的结构是这样定义的:
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);
}
}
有什么建议吗?
【问题讨论】:
-
你能显示你得到的输出吗?另外,我强烈建议将
fopen和fcloseout 退出循环。没有理由继续打开和关闭文件。 -
为什么没有在函数名前指定返回类型?
-
你怎么知道你总是得到相同的两个“随机”数字?