| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- /*
- * 示例14:结构体(Structures)
- * 功能:学习使用结构体将不同类型的数据组合在一起
- */
- #include <stdio.h>
- #include <string.h>
- // 定义一个结构体类型 Student(学生)
- // struct 关键字用于定义结构体
- struct Student {
- char name[20]; // 姓名
- int age; // 年龄
- float score; // 成绩
- };
- int main() {
- // 声明一个 Student 类型的变量
- struct Student stu1;
- // 给结构体的成员赋值
- // 使用点号 . 访问结构体的成员
- strcpy(stu1.name, "小明");
- stu1.age = 18;
- stu1.score = 92.5;
- // 输出结构体的成员
- printf("=== 学生信息 ===\n");
- printf("姓名:%s\n", stu1.name);
- printf("年龄:%d\n", stu1.age);
- printf("成绩:%.1f\n", stu1.score);
- // 声明并初始化结构体的另一种方式
- struct Student stu2 = {"小红", 19, 88.0};
- printf("\n=== 第二个学生 ===\n");
- printf("姓名:%s,年龄:%d,成绩:%.1f\n",
- stu2.name, stu2.age, stu2.score);
- // 结构体数组:存储多个学生
- printf("\n=== 学生数组 ===\n");
- struct Student students[3] = {
- {"张三", 20, 85.5},
- {"李四", 21, 90.0},
- {"王五", 19, 78.5}
- };
- // 遍历输出所有学生
- for (int i = 0; i < 3; i++) {
- printf("第 %d 个学生:%s,年龄 %d,成绩 %.1f\n",
- i + 1, students[i].name, students[i].age, students[i].score);
- }
- return 0;
- }
|