1
0

14_structs.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * 示例14:结构体(Structures)
  3. * 功能:学习使用结构体将不同类型的数据组合在一起
  4. */
  5. #include <stdio.h>
  6. #include <string.h>
  7. // 定义一个结构体类型 Student(学生)
  8. // struct 关键字用于定义结构体
  9. struct Student {
  10. char name[20]; // 姓名
  11. int age; // 年龄
  12. float score; // 成绩
  13. };
  14. int main() {
  15. // 声明一个 Student 类型的变量
  16. struct Student stu1;
  17. // 给结构体的成员赋值
  18. // 使用点号 . 访问结构体的成员
  19. strcpy(stu1.name, "小明");
  20. stu1.age = 18;
  21. stu1.score = 92.5;
  22. // 输出结构体的成员
  23. printf("=== 学生信息 ===\n");
  24. printf("姓名:%s\n", stu1.name);
  25. printf("年龄:%d\n", stu1.age);
  26. printf("成绩:%.1f\n", stu1.score);
  27. // 声明并初始化结构体的另一种方式
  28. struct Student stu2 = {"小红", 19, 88.0};
  29. printf("\n=== 第二个学生 ===\n");
  30. printf("姓名:%s,年龄:%d,成绩:%.1f\n",
  31. stu2.name, stu2.age, stu2.score);
  32. // 结构体数组:存储多个学生
  33. printf("\n=== 学生数组 ===\n");
  34. struct Student students[3] = {
  35. {"张三", 20, 85.5},
  36. {"李四", 21, 90.0},
  37. {"王五", 19, 78.5}
  38. };
  39. // 遍历输出所有学生
  40. for (int i = 0; i < 3; i++) {
  41. printf("第 %d 个学生:%s,年龄 %d,成绩 %.1f\n",
  42. i + 1, students[i].name, students[i].age, students[i].score);
  43. }
  44. return 0;
  45. }