C语言描述-年龄比较算法-存活数法和比较法

发布者: 站长-R 分类: C++/C,IT技术交流,算法 发布时间: 2025-12-10 23:48 访问量: 122 次浏览

首先创建两个结构体,一个描述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;
}

算法比较

特性算法二(直接比较)算法一(计算天数)
准确性(有误差)
复杂度简单复杂
需要当前日期不需要需要
计算量只有比较需要乘法和加法
适用场景比较年龄大小需要确切年龄值

如果只是比较谁更年轻/年长:使用直接比较算法
如果需要计算确切年龄(天数):使用改进的准确计算方法

    如果觉得本站对您有帮助,请随意赞赏。您的支持将鼓励本站走向更好!!

    发表回复

    您的邮箱地址不会被公开。 必填项已用 * 标注