这是我发布的第一个文章。。。
本人计算机大一新手,想把自己近来遇到的一些问题分享给大家,避免踩坑。
在这道题中,其实关于链表的建立是比较基础的,但是在最后有一个当输入“#”时结束。
由于姓名都是以字符串的形式输入的,所以这里的“#”应该是字符串,但是如何判断是否为“#”呢?
刚开始我想的是用“==”,但是发现错误,后来经过网上查询明白,字符串的比较不能用“==”,而应该用strcmp函数。此函数在两者相等时返回“0”,不等时返回非0值。所以后面就比较轻松了。
#include<stdio.h>
#include<stdlib.h>
struct stu
{
double xh;
char name[80];
int cj;
struct stu* next;
};
struct stu* list(struct stu *p)
{
struct stu *head,*q;
head=NULL;
q=(struct stu*)malloc(sizeof(struct stu));
while(p->xh)
{
if(head==NULL)
head=p;
else
q->next=p;
q=p;
p=(struct stu*)malloc(sizeof(struct stu));
scanf("%lf%s%d",&p->xh,p->name,&p->cj);
}
q->next=NULL;
free(p);
return head;
}
void print(struct stu* h)
{
int i=0;
double count=0;
while(h!=NULL)
{
printf("%.0lf %s %d\n",h->xh,h->name,h->cj);
count=count+h->cj;
i++;
h=h->next;
}
printf("%.2lf\n",count/i);
}
int main()
{
struct stu* h;
struct stu *p;
p=(struct stu*)malloc(sizeof(struct stu));
while(scanf("%lf%s%d",&p->xh,p->name,&p->cj)!=EOF)
{
h=list(p);
print(h);
p=(struct stu*)malloc(sizeof(struct stu));
}
}
以上为代码,欢迎大家有更优解分享。