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
,我似乎無法弄清楚原因。任何幫助表示讚賞,謝謝!
哦,我看看,謝謝你的狀態!你能告訴我如何在我的代碼中更改lib的成員嗎? – drawar 2013-05-07 16:50:58
不客氣。假設'lib'是一個全局變量,'lib [i] = *(lib [i] .nextedition)'行似乎改變了它。 – simonc 2013-05-07 16:52:09
啊,明白了,謝謝你爲我清理! – drawar 2013-05-07 16:56:10