第 9 章 结构
【练习9-1】定义一个能够表示复数的结构类型,一个复数包括实数与虚数两个
部分。
解答:
struct complex{
float real;
float imaginary;
};
【练习9-2】人的出生日期由年、月、日组成,请在例 9-1 中的通讯录结构中
增加一个成员:出生日期,用嵌套定义的方式重新定义该结构类型。
解答:
struct date{
int year;
int month;
int day;
};
struct student{
int num;
char name[10];
struct date birthday;
int computer,english,math;
double average;
};
【练习9-3】例 9-1 中,如果要计算的是三门课程的课程平均成绩,应该如何改
写程序?
解答:
#include
struct student{
int num;
char name[10];
int computer,english,math;
double average;
};
int main(void)
{
int i, n;
double math_sum,english_sum,computer_sum;
struct student s1;
printf("Input n:");
scanf("%d", &n);
printf("Input the student's number, name and course scores:\n");
math_sum=english_sum=computer_sum=0;
for(i=1;i<=n;i++){
printf("No.%d:",i);
scanf("%d%s%d%d%d",&s1.num,,&s1.math,&s1.english,&pu
ter);
math_sum+=s1.math;
english_sum+=s1.english;
computer_sum+=puter;
}
printf("math_ave:%.2lf\nenglish_ave:%.2lf\ncomputer_ave:%.2lf\n",
math_sum/n,english_sum/n,computer_sum/n);
return 0;
}
【练习9-4】定义一个包含 5 名学生信息的结构数组,并对该结构数组的所有元
素进行初始化。
解答:
struct student{
int num;
char name[10];
int computer, english, math;
};
struct student s[5]={{30101,"张一",69,75,84 },{30132,"李二",80,85,9
0},{40231, "王三",71,91,74},{40754, "赵四",65,76,87},{50426, "刘五",81,9
2,73}};
【练习9-5】参考例 9-2,输入并保存 10 个学生的成绩信息,分别输出平均成
绩最高和最低的学生信息。
解答:
#include
struct student{
int num;
char name[10];
int computer,english,math;
double average;
};
int main(void)
{
int i,n,max,min;
struct student students[50];
printf("Input n:");
scanf("%d",&n);
for(i=0;i
printf("Input the info of No.%d:\n",i+1);
printf("number:");
scanf("%d",&students[i].num);
printf("name:");