我需要创建一个循环,找到最老的学生并打印他的ID

时间:2013-11-01 16:44:32

标签: c loops search dynamic-memory-allocation

首先我会解释我的任务。对于这个分配,我必须使用动态内存分配,我没有遇到任何问题。我遇到的问题是找出正确的工作方式。对于我的任务,我需要创建一个程序,提示用户输入他们有多少学生,然后要求提供以下信息;学生证,出生日期和电话号码。我需要使用循环来提示用户输入所有学生信息。我需要创建一个循环,扫描所有学生ID并使用他们的生日找到最老的学生(循环必须能够扫描超过3名学生)。

这是我的代码,我已经从你们那里得到了一些建议,甚至还有一些代码。这是我的代码什么是创建循环的最佳方法,该循环将搜索所有学生并找到最老的?

谢谢。

#include <stdio.h>
#include <stdlib.h>

struct studentDataType
{
    int studentID;
    int year;
    int month;
    int day;
    long long phone;
};

int main (void)
{
    struct studentDataType *studentRecords=NULL;
    unsigned int students;
    unsigned int studentID;
    unsigned int year;
    unsigned int month;
    unsigned int day;
    unsigned long phone;

    printf("How many students are you entering records for:\n");
    scanf("%d", &students);

    studentRecords = malloc(sizeof(struct studentDataType) * students);
    int i=0;
    for (i; i != students ; ++i)  {
        printf("Enter information for student as follows (ID, DOB year, DOB month, DOB day, Phone): %d\n", i+1);
        struct studentDataType * s = &studentRecords[i];
        scanf("%u %u %u %u %u", &(s->studentID), &(s->year), &(s->month), &(s->day), &(s->phone));
    }
}

1 个答案:

答案 0 :(得分:1)

首先用零初始化本地“日期”(即可能的最小日期)。然后遍历集合中的所有条目。当您找到具有比本地更早的“日期”的结构时,将索引保存到该条目并将本地日期设置为条目日期。然后当循环结束时,保存的索引是“最旧的”条目。

像这样的伪代码

oldest_date = 0;
oldest_index = -1;

loop_over_all_students
{
    if current_student.date > oldest_date
    {
        oldest_date = current_student.date
        oldest_index = current_index
    }
}

if (oldest_index >= 0)
{
    /* The variable `oldest_index` is the index to the "oldest" student */
}