69,371
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
struct num_list {
int num;
struct num_list *next;
};
struct num_list *num_list_append(struct num_list *list, int num)
{
struct num_list *node = (struct num_list*)calloc(1, sizeof(struct num_list));
node->next = list;
node->num = num;
return node;
}
struct num_list *scan(const char *text)
{
struct num_list *list = 0;
int num, pos = 0;
while (text[pos]) {
if (isdigit(text[pos])) {
sscanf(text+pos, "%d", &num);
list = num_list_append(list, num);
while (isdigit(text[pos])) {
++pos;
}
} else {
++pos;
}
}
return list;
}
int main(void)
{
struct num_list *list = scan("123ab456\r\n1.3");
int sum = 0, count = 0;
while (list) {
sum += list->num;
++count;
list = list->next;
}
printf("Sum: %d\n", sum);
printf("Average: %.3f", (double)sum / count);
return 0;
}
读取文本文件之后,数据传入scan即可,返回一个链表,每个节点包含一个数值。之后在main里遍历链表,计算总和以及平均值。