我的计划中的错误在哪里? (按年龄分类)

时间:2016-10-31 08:59:09

标签: c

我正在尝试按年龄对人进行排序,但不知何故,几个月和几年都会被其他人的价值所覆盖。我已经尝试找错了但没有成功。

void sortPersonsByAge(struct person *first, int cnt) {
    int i, j;
    struct person *oldest = first;

    for (j = 0; j < cnt-1; j++)
    {
        oldest = first + j;
        for (i = j; i < cnt; i++)
        {
            struct person *person = first + i;
            if (person->year_of_birth < oldest->year_of_birth)
                oldest = person; // es gibt einen neuen Altersrekord
            else if (person->year_of_birth = oldest->year_of_birth) 
            // in this else if is the mistake somewhere
            {
                if (person->month_of_birth < oldest->month_of_birth)
                    oldest = person;
                else if (person->month_of_birth = oldest->month_of_birth)
                    if (person->day_of_birth < oldest->day_of_birth)
                        oldest = person;
            }
        }
        // let's swap the first person with the oldest person

        struct person tmp; // Zwischenspeicher
        tmp = *(first+j);
        *(first+j) = *oldest;
        *oldest = tmp;
    }
}

1 个答案:

答案 0 :(得分:4)

陈述中的条件

    else if (person->year_of_birth = oldest->year_of_birth)

    else if (person->month_of_birth = oldest->month_of_birth)

始终为真(假设oldest->year_of_birtholdest->month_of_birth不为零),因为赋值运算符=的值为它的右侧价值。

您可能想要比较的运算符,即==(双=)。