一.实验目的:
1.学习掌握结构化数据的编程使用
二、实验内容和步骤 |
1.分析并修改下面程序错误,使之能够正常运行。
错误代码一:
程序实现输出图书的名字和单价,错误代码如下:
#include
struct book
{
float price;//价格
char name[10];//名字
}
int main(void)
{
struct book myBook;
myBook={5.6,"theworld is flat"};
printf("bookname=%s,book price=%f",myBook.name,myBook.price);
return 0;
}
错误分析:
1. 定义结构体变量错误
2. 数组name不够大
2. 编写程序实现以下功能
(1)设计一个保存学生成绩信息的结构,包括学号、姓名、课程名、平时成绩、考试成绩、总评成绩。分别用函数实现以下功能:
①输入n个学生的信息(平时和考试成绩)
②要求计算并输出学生的总分(平时20%,考试80%)并输出;
③输出总分最高和最低的学生信息。
代码:
#include
#include
#include
#define n 3
struct course
{
floatcommon_score,exam_score;
};
struct student
{
int num;
charname[10];
structcourse Chi,Math,Eng;
floattotal_scor;
};
void input(struct student stu[])
{
int i=n;
for(i=1;i<=n;i++)
{
printf("Please input %s's common,exam score ofChinese:\n",stu[i].name);
scanf("%f%f",&stu[i].Chi.common_score,&stu[i].Chi.exam_score);
printf("Please input %s's common,exam score ofMath:\n",stu[i].name);
scanf("%f%f",&stu[i].Math.common_score,&stu[i].Math.exam_score);
printf("Please input %s's common,exam score ofEnglish:\n",stu[i].name);
scanf("%f%f",&stu[i].Eng.common_score,&stu[i].Eng.exam_score);
stu[i].total_scor=
(stu[i].Chi.common_score+stu[i].Math.common_score+stu[i].Eng.common_score)*0.2
+(stu[i].Chi.exam_score+stu[i].Math.exam_score+stu[i].Eng.exam_score)*0.8;
}
}
void output1(struct student stu[])
{
int i=n;
printf("Their total score is:\n");
for(i=1;i<=n;i++)
{
printf("%.3f\n",stu[i].total_scor);
}
}
void output2(struct student stu[])
{
inti=n,t1,t2;
floatmax,min,t;
max=min=stu[i].total_scor;
t1=t2=1;
for(i=2;i<=n;i++)
{
if(stu[i].total_scor>max)
{
t=stu[i].total_scor;
stu[i].total_scor=max;
max=t;
t1=i;
}
if(stu[i].total_scor
{
t=stu[i].total_scor;
stu[i].total_scor=min;
min=t;
t2=i;
}
}
printf("The highest score %f's number is %d,name is %s\nThe lowestscore %f's number is %d,name is %s\n",
max,stu[t1].num,stu[t1].name,min,stu[t2].num,stu[t2].name);
}
int main()
{
structstudent stu1[n];
int i;
stu1[1].num=1;
for(i=2;i<=n;i++)
{
stu1[i].num++;
}
strcpy(stu1[1].name,"Harden");
strcpy(stu1[2].name,"James");
strcpy(stu1[3].name,"Durant");
input(stu1);
output1(stu1);
output2(stu1);
return 0;
}