《C语言》结构体和联合体练习题--1
《C语言》结构体和联合体练习题–1
1. 定义和初始化结构体
题目描述:
编写一个C程序,定义一个名为Person
的结构体,包含成员name
(字符串)、age
(整数)和height
(浮点数)。然后,初始化一个Person
类型的变量,并输出其成员的值。
解题思路:
首先,定义一个结构体Person
,包含所需的成员。然后,在主函数中声明一个Person
变量,并使用初始化列表为其成员赋值。最后,使用printf
函数输出各成员的值。
详细代码:
#include <stdio.h>// 定义结构体Person
struct Person {char name[50];int age;float height;
};int main() {// 初始化结构体变量struct Person person = {"Alice", 30, 5.6f};// 输出结构体成员的值printf("姓名: %s\n", person.name);printf("年龄: %d\n", person.age);printf("身高: %.1f 英尺\n", person.height);return 0;
}
代码注释:
struct Person
:定义一个结构体类型Person
,包含name
、age
和height
三个成员。char name[50];
:声明一个字符数组用于存储姓名,最大长度为49个字符(留出一个字符用于字符串结束符\0
)。struct Person person = {"Alice", 30, 5.6f};
:使用初始化列表为结构体变量person
的成员赋值。printf
:分别输出结构体成员的值。
2. 访问结构体成员
题目描述:
编写一个C程序,定义一个结构体Rectangle
,包含成员length
和width
(均为浮点数)。输入一个Rectangle
的length
和width
,计算并输出其面积和周长。
解题思路:
定义结构体Rectangle
,包含length
和width
。在主函数中声明一个Rectangle
变量,使用scanf
函数读取用户输入的长度和宽度。然后,计算面积(length × width)和周长(2 × (length + width)),并输出结果。
详细代码:
#include <stdio.h>// 定义结构体Rectangle
struct Rectangle {float length;float width;
};int main() {struct Rectangle rect;float area, perimeter;// 输入长度和宽度printf("请输入矩形的长度: ");scanf("%f", &rect.length);printf("请输入矩形的宽度: ");scanf("%f", &rect.width);// 计算面积和周长area = rect.length * rect.width;perimeter = 2 * (rect.length + rect.width);// 输出结果printf("矩形的面积是: %.2f\n", area);printf("矩形的周长是: %.2f\n", perimeter);return 0;
}
代码注释:
struct Rectangle
:定义一个结构体类型Rectangle
,包含length
和width
两个浮点数成员。scanf
:读取用户输入的长度和宽度,并存储到结构体变量rect
的相应成员中。area
和perimeter
:计算并存储面积和周长。printf
:输出计算结果。
3. 嵌套结构体
题目描述:
编写一个C程序,定义两个结构体Date
和Employee
。Date
包含成员day
、month
和year
。Employee
包含成员name
(字符串)、id
(整数)和birthdate
(类型为Date
的结构体)。输入一个员工的详细信息,并输出。
解题思路:
首先,定义结构体Date
和Employee
,其中Employee
包含一个Date
类型的成员birthdate
。在主函数中声明一个Employee
变量,使用嵌套的scanf
函数读取员工的姓名、ID和生日。最后,使用printf
函数输出员工的详细信息。
详细代码:
#include <stdio.h>// 定义结构体Date
struct Date {int day;int month;int year;
};// 定义结构体Employee,包含Date类型的成员birthdate
struct Employee {char name[50];int id;struct Date birthdate;
};int main() {struct Employee emp;// 输入员工姓名printf("请输入员工姓名: ");fgets(emp.name, sizeof(emp.name), stdin);// 去除换行符int i = 0;while(emp.name[i] != '\0') {if(emp.name[i] == '\n') {emp.name[i] = '\0';break;}i++;}// 输入员工IDprintf("请输入员工ID: ");scanf("%d", &emp.id);// 输入员工生日printf("请输入员工生日(格式: 日 月 年): ");scanf("%d %d %d", &emp.birthdate.day,