第1部分 程序改错题
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
第1部分程序改错题
第1题
在主函数中从键盘输入若干个数放入数组中,输入0结束输入并放在最后一个元素中。给定程序MODI0.C中函数fun的功能是:计算数组中值为正数的平均值(不包括0)。例如:数组中元素的值依次为:39,-47,21,2,-8,15,0,则程序的运行结果为:19.25。
请改正函数fun中的错误,使它能输出正确的结果。
注意:不要改动main函数,不得增行或删行,也不得更改程序的结构!
#include
#include
double fun (int x[])
{
int sum=0.0;
int c=0,i=0;
while(x[i]!=0)
{
if (x[i]>0)
{
sum+=x[i];
c++
}
i++;
}
sum\=c;
return sum;
}
main()
{
int x[1000]; int i=0;
clrscr();
printf("\nPlease enter some data (end with 0):");
do {
scanf("%d",&x[i]);
} while (x[i++]!=0);
printf("%f\n",fun(x));
}
第2题
学生花名册可以用结构体型链表存放。
结构中包含成员学号(int xh)、姓名(char xm[8])、性别(char sex)、班级号(int bj)、成绩(int cj),sex='m'表示男学生,'w'为女学生,班级序号bj为1至9。该结构已用typedef 定义为数据类型STUDENT。给定程序FILL0.C就建立了这样一个链表,函数ftotal()的功能是:统计各班的平均成绩。
请改正函数ftotal中的错误,使它能计算出正确的结果。
注意:不要改动main函数,不得增行或删行,也不得更改程序的结构!
#include
#include
typedef struct STUDENT{
long xh;
char xm[8];
char sex;
int bj;
int cj;
struct STUDENT * next;
};
void ftotal(struct STUDENT *head,int a[])
{
struct STUDENT * p;
int b[9],i;
p=head;
for(i=0;i<9;i++)
{
a[i]=0;
b[i]=0;
}
while(p)
{
a[p->bj-1]=p->cj;
b[p->bj-1]=1;
p=p->next;
}
for(i=0;i<9;i++)
if (b[i]) a[i]=a[i]/b[i];
else a[i]=0;
}
void finput(struct STUDENT *head)
{
struct STUDENT * p;
p=head;
while(p)
{
printf("\nPlease nput the score of class %d the student %s :",p->bj,p->xm);
scanf("%d",&p->cj);
p=p->next;
}
}
struct STUDENT * fsetup()
{
struct STUDENT *h,*p,*p1;
h=NULL;
p1=NULL;
while(1)
{
p=(struct STUDENT * )malloc (sizeof(struct STUDENT));
scanf("%ld %s %c %d",&p->xh,p->xm,&p->sex,&p->bj);
p->cj=0;
if (p->xh==0)
{
free(p);
if (p1) p1->next=NULL;
break;
} else {
if(h==0){h=p;p1=p;}
else {p1->next=p;p1=p;}
}
}
return h;
}
print(struct STUDENT * head)
{
struct STUDENT * p;
p=head;
while(p)
{
printf("%08ld,%-8s,%c,%1d,%3d\n",p->xh,p->xm,p->sex,p->bj,p->cj);
p=p->next;
}
printf("\n");
}
main()
{
struct STUDENT *h;
int a[9],i;
h=fsetup();
print(h);
finput(h);
print(h);
ftotal(h,a);