C语言结构体数组:寻找最年长学生
C语言结构体数组:寻找最年长学生
在这篇博客中,我们将探讨如何使用C语言的结构体和数组来存储一组学生的姓名和出生日期,并编写一个函数来确定最年长的学生。
代码实现c#include 'allinclude.h'
// 定义日期结构体struct date { int year; int month; int day;};
// 定义学生结构体,包含姓名和出生日期struct student { char name[20]; struct date birth;};
// 找到最年长学生的函数char* oldest(struct student s[], int n) { // 初始化最年长学生的名字为第一个学生的名字 char* t = s[0].name; // 遍历学生数组 for (int i = 1; i < n; i++) { // 比较学生的出生年份 if (s[i].birth.year < s[i-1].birth.year || // 如果出生年份相同,则比较月份 (s[i].birth.year == s[i-1].birth.year && s[i].birth.month < s[i-1].birth.month) || // 如果出生年份和月份都相同,则比较日期 (s[i].birth.year == s[i-1].birth.year && s[i].birth.month == s[i-1].birth.month && s[i].birth.day < s[i-1].birth.day)) { // 如果当前学生的出生日期更早,则更新最年长学生的名字 t = s[i].name; } } // 返回最年长学生的名字 return t;}
代码解释
- 我们首先定义了两个结构体:
date和student。date结构体存储年份、月份和日期,而student结构体包含学生的姓名和出生日期。2.oldest函数接受一个student结构体数组和数组大小作为输入。它返回最年长学生的姓名。3. 在oldest函数中,我们初始化t为第一个学生的姓名。4. 然后,我们遍历数组并比较每个学生的出生日期。5. 如果当前学生的出生日期早于t中存储的日期,我们将t更新为当前学生的姓名。6. 最后,函数返回t,即最年长学生的姓名。
总结
这段代码演示了如何使用C语言结构体数组来存储和处理学生信息,并有效地找到最年长的学生。
请注意,allinclude.h 头文件的内容需要根据您的程序需求进行定义。
原文地址: https://www.cveoy.top/t/topic/yGH 著作权归作者所有。请勿转载和采集!