定义结构
为了定义结构,您必须使用 struct 语句。struct 语句定义了一个包含多个成员的新的数据类型,struct 语句的格式如下:
struct Student
{
int sno;
char name[20];
char cname[20];
…
}stu;
Student,是结构体标签.
stu结构变量,定义在结构的末尾,最后一个分号之前,您可以指定一个或多个结构变量.
结构体变量的初始化
和其它类型变量一样,对结构体变量可以在定义时指定初始值。
#include <stdio.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book = {"C 语言", "RUNOOB", "编程语言", 123456};
int main()
{
printf("title : %s\nauthor: %s\nsubject: %s\nbook_id: %d\n", book.title, book.author, book.subject, book.book_id);
}
输出结果:
title : C 语言
author: RUNOOB
subject: 编程语言
book_id: 123456
例题:
输出结构体数组中年龄最大者的数据 (10 分)
给定程序中,函数fun的功能是:将形参std所指结构体数组中年龄最大者的数据作为函数值返回,并在主函数中输出。
函数接口定义:
struct student fun(struct student std[], int n);
其中 std 和 n 都是用户传入的参数。 函数fun的功能是将含有 n 个人的形参 std 所指结构体数组中年龄最大者的数据作为函数值返回。
裁判测试程序样例:
#include <stdio.h>
struct student
{char name[10];
int age;
};
struct student fun(struct student std[], int n);
int main()
{
struct student std[5]={“aaa”,17,“bbb”,16,“ccc”,18,“ddd”,17,“eee”,15 };
struct student max;
max=fun(std,5);
printf("\nThe result:\n");
printf("\nName : %s, Age : %d\n", max.name,max.age);
return 0;
}
/* 请在这里填写答案 */
输出样例:
The result:
Name : ccc, Age : 18
struct student fun(struct student std[], int n)
{
struct student max;
int i;
max=*std;
for(i=0;i<n;i++)
{
if(max.age<std[i].age)
max=std[i];
}
return max;
}
7-2 查找成绩最高的学生 (10 分)
编写程序,从键盘输入 n (n<10)个学生的学号(学号为4位的整数,从1000开始)、成绩并存入结构数组中,查找并输出成绩最高的学生信息。
输入输出示例:括号内为说明,无需输入输出
输入样例:
3 (n=3)
1000 85
1001 90
1002 75
输出样例:
1001 90
#include <stdio.h>
#define N 8
typedef struct student
{
int no;
int score;
}student;
int main()
{
student s[1000];
int n,i;
int max;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&s[i].no);
scanf("%d",&s[i].score);
max=s[0].score;
if(max<s[i].score)
max=s[i].score;
}
for(i=0;i<n;i++)
{
if(s[i].score==max)
printf("%d ",s[i].no);
}
printf("%d",max);
return 0;
}
学生排序 (10 分)
编写程序,从键盘输入 n (n<10)个学生的学号(学号为4位的整数,从1000开始)、成绩并存入结构数组中,按成绩从低到高排序并输出排序后的学生信息。
输入输出示例:括号内为说明,无需输入输出
输入样例:
3 (n=3)
1000 85
1001 90
1002 75
输出样例:
1002 75
1000 85
1001 90
#include <stdio.h>
#define N 8
typedef struct student
{
int no;
int score;
}student;
int main()
{
student s[1000];
int n,i,j;
int temp;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d %d",&s[i].no,&s[i].score);
}
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(s[j].score>s[j+1].score)//对分数排序
{
temp=s[j].score;
s[j].score=s[j+1].score;
s[j+1].score=temp;
//分数排序完毕后,学号也要交换
temp=s[j].no;
s[j].no=s[j+1].no;
s[j+1].no=temp;
}
}
}
for(i=0;i<n;i++)
{
printf("%d %d\n",s[i].no,s[i].score);
}
return 0;
}