2013-10-01 67 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等等以後都沒有得到任何東西。