二叉搜索树查询选课学生成绩均值结果为0的问题排查
Hey Devin, let's dig into that average grade issue you're facing—sounds like everything else is clicking except this one calculation, which is super frustrating! Let's break down the most likely culprits based on what you described.
First off, double-check that you're actually adding up each grade correctly when calculating the total. It's easy to slip up here:
- Did you use
total += current->gradeinstead of accidentally reassigning withtotal = current->grade? The latter would overwrite the total every time, leaving you with only the last grade (or 0 if the list is empty). - Is your loop properly traversing the entire grades linked list? Make sure your loop condition is
current != NULLand that you're moving to the next node withcurrent = current->nextinside the loop. Example of what correct code might look like:int total_grades = 0; int grade_count = 0; GradeNode* temp = student->grade_list; while (temp != NULL) { total_grades += temp->score; grade_count++; temp = temp->next; }
Your hunch about integer types is spot-on—this is a super common pitfall!
- If both
total_gradesandgrade_countare integers, dividing them will use integer division, which truncates decimals. But if your result is always 0, that suggests either:- The
total_gradesvariable is staying at 0 (meaning your accumulation logic is broken), or grade_countis 0 (you're not counting grades correctly, or the student has no grades assigned), leading to undefined behavior (but some compilers/runtimes might output 0 here).
- The
- To fix this, cast one of the values to a floating-point type before division to get a decimal average:
double average = (double)total_grades / grade_count;
Even though you can print student info, take a second to verify that the grades you think are stored are actually there. Add a quick debug print before calculating the average to check the total and count:
printf("Debug: %s's total grades = %d, count = %d\n", student->name, total_grades, grade_count);
If this outputs total=0 and count=0, your grades aren't being added to the linked list properly—go back and check how you're appending grades to the student's list.
If you're calculating an average across the entire roster, make sure your binary search tree traversal is visiting every student node. It's easy to miss a left or right subtree in recursive or iterative traversal code, which could mean you're only sampling a subset of students (or none at all, leading to a total of 0).
内容的提问来源于stack exchange,提问作者Devin

