提醒一下:不要试图一揽子做,讲究效率,会想到只遍历一次把所有功夫做完,但那样只会令你写出意大利面条代码,给以后的维护和扩展带来麻烦,所以不要那样做,老老实实逐个功能写,在这个过程中,尽量把可重复使用的代码提炼成函数,不过这是后话,目前先逐个完成功能再说,写多了,自然看得出哪些代码是重复的、以及如何提炼成函数。

授人以渔,不授人以鱼。

2014-12-12 23:39
2014-12-13 00:15
2014-12-13 00:19
程序代码:
#include <stdio.h>
#include <stdlib.h>
#define N 5
struct student {
int num;
char name[20];
float score[3];
struct student *next;
};
float avg[N] = {0.0};
float *average(struct student *p) {
int i = 0;
while(p != NULL) {
avg[i] = (p->score[0] + p->score[1] + p->score[2]) / 3.0;
p = p->next;
i++;
}
return (avg);
}
struct student *create(int n) {
struct student *head, *last, *p;
int i;
head = last = p = NULL;
printf("Input student num name score1 score2 score3:\n");
p = (struct student *)malloc(sizeof(struct student));
if(p == NULL) {
printf("malloc error!\n");
exit(1);
}
p->next = head;
head = p;
scanf("%d%s%f%f%f", &p->num, p->name,
&p->score[0], &p->score[1], &p->score[2]);
for(i = 1; i < n; i++) {
last = p;
while(last->next != NULL) {
p->next = last;
}
p = (struct student *)malloc(sizeof(struct student));
last->next = p;
p->next = NULL;
scanf("%d%s%f%f%f", &p->num, p->name,
&p->score[0], &p->score[1], &p->score[2]);
}
return (head);
}
void output(struct student * p) {
int i = 0;
average(p);
printf("num\tname\tscore\t\t\tavg\n");
while(p != NULL) {
printf("%d\t%s\t%.2f\t%.2f\t%.2f\t%.2f\n",
p->num, p->name,
p->score[0], p->score[1], p->score[2],
avg[i]);
p = p->next;
i++;
}
}
int main(void) {
struct student *stu;
stu = create(N);
output(stu);
return 0;
}

2014-12-13 03:33
2014-12-13 10:13


2014-12-13 10:27
2014-12-13 10:35

2014-12-13 11:14