2013-10-01 66 views
0

我有一个链接列表,它从文件中读取一些信息并将其显示在屏幕上。一切正常,但是当我去显示“秒”时,显示的数字是类似于-431602080.000000而不是,例如,27.123000。我不知道为什么。打印链接列表的浮动元素显示不正确?

//GLOBAL VARIABLES 
    struct PlayerTime* list_head = NULL; 

    void besttimes_view() 
    { 
     struct PlayerTime *p; 
     p = list_head; 

     while(p!=NULL){ 
      printf("%f : %s\n", p->seconds, p->name); //This prints the name correctly, but the number is wrong. Something like -431602080.000000 : Calvin 
      p = p->next; 
     } 
    } 

任何人有任何想法是怎么回事?

+0

你是否知道你只是为你创建的第一个元素设置'p->秒',而你永远不会添加到这个列表中? –

+0

@ rphello101,如果您不希望StackOverFlow上的代码继续并删除问题。我看到有人编辑了这个问题,没有意识到是你,开始回滚,然后看到它是你,将它回滚到你的编辑。无论如何,这是你的问题,你可以随心所欲地做任何事情。 –

+0

我无法删除该问题,因为有回复 - 尽管任何版主阅读此内容,都可以随时删除该问题。我的学校剽窃软件贴上了过多的代码。显然它违反了版权,因为我没有自己编写所有的代码。我尽可能多地抹去了我认为会让问题难以理解的问题。我还需要做其他几个问题。 – rphello101

回答

2
while((fgets(input,MAX_STR_LEN,fileName)!=NULL)){ 
    p=(struct PlayerTime*)malloc(sizeof(struct PlayerTime)); 

您的malloc新playertime每个与fgets(),但你只把它添加到列表 每隔与fgets()。你添加到列表中的那个没有设置 秒,只有名字。

换句话说,您已设置秒数的playatime,永远不会将 添加到列表中。只有您设置了名称的人才会被添加到列表中。

if(counter==1){ 
     p->seconds=atof(input); // this p is never added to the list 
     printf("%f\n",p->seconds); //This prints the number as it should be (e.g. 27.123000) 
    } 
    if(counter==2){ 
     strcpy(p->name,input); // this p is added to the list 
     counter=0; 
     p->next=list_head; 
     list_head = p; 
    } 
1

我会用事实,你的counter==1分支之外的分配p开始。换句话说,您:

  1. 分配一个新的p
  2. counter==1,所以你把时间在里面,
  3. 增加counter
  4. 分配一个新的p(并丢弃前一个)
  5. counter==2,所以你把它的名字和存储它,
  6. ...

我想你想malloc()发生在if (counter==1)里面。

然后,你不重置计数器,所以每个下一个玩家自从counter==3等等以后都没有得到任何东西。