我是新来的,所以请在解释我的问题时请耐心等待
我正在尝试创建一个函数,其中查找销售额最多的日期。我这样做是通过读取包含以下内容的文件中的数据来实现的:
date, item, count
我正在使用链接列表来过滤链表中的所有销售结构(按日期排序)
这是我的结构:
typedef struct sales {
int amount;
char *date;
struct stockItem *item;
struct sales *next;
} sales;
以下是查找哪一天销售额最高的代码:
sales *sFirstNode = NULL;
sales *sLastNode = NULL;
int findHighestVolumeSales() {
char *previousDate = NULL;
struct sales *tmpPtr = sFirstNode;
struct sales *tmpNxt = sFirstNode->next;
char *currentDate = tmpPtr->date;
int tmp=0;
int mostSales;
while(tmpNxt != NULL){
while(tmpNxt != tmpPtr){
if(currentDate == previousDate){
tmp = tmpPtr->amount + tmp;
}
else{
tmp = tmpPtr->amount;
}
if(tmp > mostSales){
mostSales = tmp;
printf("%d\n", mostSales);
}
previousDate = tmpPtr->date;
tmpPtr = tmpPtr->next;
}
tmpPtr = sFirstNode;
tmpNxt = tmpNxt->next;
}
printf("%d\n", mostSales);
return mostSales;
}
函数返回的值似乎是地址而不是mostSales本身。
我收到了:
6421718
价值很大,但没有这么大。我确定我的代码存在问题
编辑:
int findHighestVolumeSales() {
char *previousDate = NULL;
struct sales *tmpPtr = sFirstNode;
struct sales *tmpNxt = sFirstNode->next;
char *currentDate = NULL;
int tmp=0;
int mostSales =0;
while(tmpNxt != NULL){
currentDate = tmpPtr->date;
while(tmpNxt != tmpPtr){
// printf("%d \n", mostSales);
if(currentDate == previousDate){
tmp = tmpPtr->amount + tmp;
}
else{
tmp = tmpPtr->amount;
}
if(tmp > mostSales){
mostSales = tmp;
printf("%d\n", mostSales);
}
previousDate = tmpPtr->date;
tmpPtr = tmpPtr->next;
}
tmpPtr = sFirstNode;
tmpNxt = tmpNxt->next;
}
printf("%d\n", mostSales);
return mostSales;// Place holder
}
答案 0 :(得分:5)
如果列表按日期顺序排列,您甚至不需要两个嵌套循环。另外,你忽略了初始化mostSales = 0;
我继续测试日期指针的相等性,但是没有说它意味着什么。您可能需要修复日期的char数组。
int findHighestVolumeSales() {
struct sales *tmpPtr = sFirstNode;
char *currentDate; // perhaps array is needed
char *mostDate; // ditto
int tmp = 0;
int mostSales = INT_MIN; // <<-- initialise !!!
if(tmpPtr == NULL) { // the empty list
return 0;
}
mostDate = currentDate = tmpPtr->date; // perhaps strcpy()
while(tmpPtr != NULL){ // parse the list
if(tmpPtr->date != currentDate) { // perhaps strcmp(), don't know
if(mostSales <= tmp) { // check the max
mostSales = tmp; // stamp
mostDate = currentDate; // perhaps strcpy()
}
tmp = 0; // reset
currentDate = tmpPtr->date; // perhaps strcpy() to fixed array
}
tmp += tmpPtr->amount; // accumulate sales
tmpPtr = tmpPtr->next; // advance
}
// check loose end
if(mostSales <= tmp) { // check the max
mostSales = tmp; // stamp
mostDate = currentDate; // perhaps strcpy()
}
printf("%d on %s\n", mostSales, mostDate); // report
return mostSales;
}