N名学生的成绩已在主函数中放入一个带头节点的链表结构中,h指向链表的头节点。 请编写函数fun,它的功能是:求出平均分,由函数值返回
/N名学生的成绩已在主函数中放入一个带头节点的链表结构中,h指向链表的头节点。
请编写函数fun,它的功能是:求出平均分,由函数值返回/
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
float fun(struct Node *h)
{
int sum = 0;
int count = 0;
struct Node *current = h->next;
while (current != NULL)
{
sum += current->data;
count++;
current = current->next;
}
if (count == 0)
{
return -1;
}
return (float)sum / count;
}
int main(void)
{
int n=0;
printf("please enter student number\n");
scanf("%d",&n);
struct Node *head = (struct Node *)malloc(sizeof(struct Node));
head->next = NULL;
for (int i = 0; i < n; i++)
{
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
printf("please enter %d student score\n",i+1);
scanf("%d",&new_node->data);
new_node->next = head->next;
head->next = new_node;
}
float average = fun(head);
printf("平均成绩为: %.2f\n", average);
return 0;
}