2013-05-07 158 views
1

鑑於定義如下的結構和結構本書的數組LIB指針和結構

struct Book{ 
    char title[100]; 
    char author[100]; 
    int price; 
    struct Book *nextedition; 
}; 


struct Book lib[1000]; 

我打算寫一個函數由給定筆者計算的書籍總價包括所有未來版本的書籍,即使未來版本的作者不是指定的作者。

title author price nextedition 
---------------------------------- 
0 Book1 Author1 25  &lib[2] 
1 Book2 Author2 20  NULL 
2 Book3 Author3 30  &lib[3] 
3 Book4 Author1 35  NULL 

對於上面的例子,這本書在LIB [2]是,在LIB下一版[0],這本書在LIB [4]是,在LIB下一版[2] 。因此,給定作者「作者1」,該函數應該返回90(= 25 + 30 + 35),並給予作者「作者3」,該函數應返回65(= 30 + 35)。

所以這是我的代碼:

int firstEdition(char author[100]){ 
    int i, pos=-1; 
    for(i=0;i<numbooks;i++) 
    if(strcmp(lib[i].author,author)==0){ 
     pos=i; 
     if(pos>=0) return pos; 
    } 
    return -1; 
} 

int totalPrice(char author[100]){ 
    int price=0; 
    int i=firstEdition(author); 
    if (i<0) 
     return 0; 
    else {  
     while (lib[i].nextedition != NULL){ 
      price+=lib[i].price; 
      lib[i]=*(lib[i].nextedition); 
     } 
    return price;} 
} 

我試着運行上面的示例和作者=「作者1」的代碼,並一直得到錯誤的輸出。該函數總是返回55而不是90,我似乎無法弄清楚原因。任何幫助表示讚賞,謝謝!

回答

1

totalPrice的實施在退出其while循環之前,先考慮列表中最後一本書的價格。它也改變了lib的一些成員,這顯然不理想。

以下(未經測試)的代碼應該給你正確的price不改變lib

int totalPrice(char author[100]){ 
    int price=0; 
    int i=firstEdition(author); 
    struct Book *book; 
    if (i<0) 
     return 0; 
    book = &lib[i]; 
    while (book != NULL) { 
     price+=book->price; 
     book = book->nextedition; 
    } 
    return price; 
} 
+0

哦,我看看,謝謝你的狀態!你能告訴我如何在我的代碼中更改lib的成員嗎? – drawar 2013-05-07 16:50:58

+0

不客氣。假設'lib'是一個全局變量,'lib [i] = *(lib [i] .nextedition)'行似乎改變了它。 – simonc 2013-05-07 16:52:09

+0

啊,明白了,謝謝你爲我清理! – drawar 2013-05-07 16:56:10