C语言描述-年龄比较算法-存活数法和比较法
首先创建两个结构体,一个描述date,一个作为个体student
typedef struct date {
int year;
int month;
int day;
}date;
typedef struct student {
char name[20];
date birthday;
}student;

存活天数法
此方法即计算,个体出生日期,到目前日期的天数,但是计算复杂度高,效率低,仅提供思路,不推荐实际应用。
int liveDaysMinYear(student stu[],int n,date nowDate) {
int minLiveDays = 0;
int liveDays = 0;
int minIndex = 0;
minLiveDays = (nowDate.year - stu[0].birthday.year) * 365 + (nowDate.month - stu[0].birthday.month) * 30 + (nowDate.day - stu[0].birthday.day);
for (int i = 0; i < n; i++) {
//不考虑闰年和每个月天数不同的情况,仅提供思路
liveDays = (nowDate.year - stu[i].birthday.year) * 365 + (nowDate.month - stu[i].birthday.month) * 30 + (nowDate.day - stu[i].birthday.day);
if (liveDays < minLiveDays) {
minLiveDays = liveDays;
minIndex = i;
}
}
return minIndex;
}逐次比较法
此方法,首先比较year,如果year相同,再比较month,如果year和month均相同,比较day,再逐步的比较下,记录下,stu[]数组中出生日期最小的个体下标minIndex。
int findMinYear(student stu[],int n) {
int minIndex = 0;
date date1, date2;
for (int i = 0; i < n;i++) {
date1 = stu[minIndex].birthday;
date2 = stu[i].birthday;
if(date1.year > date2.year || (date1.year == date2.year && date1.month>date2.month)||(date1.year == date2.year && date1.month == date2.month && date1.day>date2.day) )
{minIndex = i;}
}
return minIndex;
}算法比较
| 特性 | 算法二(直接比较) | 算法一(计算天数) |
|---|---|---|
| 准确性 | 高 | 低(有误差) |
| 复杂度 | 简单 | 复杂 |
| 需要当前日期 | 不需要 | 需要 |
| 计算量 | 只有比较 | 需要乘法和加法 |
| 适用场景 | 比较年龄大小 | 需要确切年龄值 |
如果只是比较谁更年轻/年长:使用直接比较算法
如果需要计算确切年龄(天数):使用改进的准确计算方法



