将结构域传递给C

时间:2015-10-04 02:23:28

标签: c function struct

我有一个结构,我想将其字段传递给特定的函数。例如,我的结构中的一个字段是学生quiz1的测验成绩,'quiz1'。我想计算所有quizes的平均值,最大值和最小值。我想为每个计算创建一个函数,但我不知道如何将结构的特定字段传递给给定的函数。这就是我所拥有的:

结构:

 struct studentData {
        char name[30];
        int quiz1; int quiz2;
        int quiz3; int quiz4;
        int mid1; int mid2;
        int finalexam;
    } ;

平均功能:

double calcFAverage(struct studentData *record, int reccount)
{
    float  sum_F,F_avg;
    int k;
            // calculate the score sums
            for (k=0; k<reccount; k++)
            {
                sum_F += record[k].finalexam;
            }
            F_avg = sum_F/reccount;

    return F_avg;   
}

主要:

struct studentData record[100];
calcFAverage(record,reccount);

reccount变量保存结构的记录数。但是,正如您所看到的,平均功能仅针对期末考试成绩。我怎样才能使它能够传递结构中的任何字段并获得其平均值。现在我对每个领域都有一个平均函数,这实际上是一种不好的方法。

2 个答案:

答案 0 :(得分:2)

您的数据结构并非旨在支持您要执行的计算。你需要重新设计你的结构。如果您想要添加测验1结果或期末考试成绩的分数,那么您需要更多类似的内容:

enum { QUIZ1, QUIZ2, QUIZ3, QUIZ4, MID1, MID2, FINAL };

struct studentData
{
    char name[30];
    int marks[7];    
};

现在你可以使用:

double calcFAverage(struct studentData *record, int n_recs, int markid)
{
    double sum_F = 0.0
    // calculate the score sums
    for (int k = 0; k < n_recs; k++)
        sum_F += record[k].marks[markid];

    double F_avg = sum_F / n_recs;

    return F_avg;   
}

并将其命名为:

double ave = calculateFAverage(students, n_students, FINAL);

答案 1 :(得分:0)

与Yakumo的评论一样,使用数据对齐。另一个可能更好的选择是将分数放在一个数组中,就像另一个答案一样。例如:

int quiz1offset = (int)(&(record[0].quiz1)) - (int)(record);//This is the location of quiz1 relative to the location of its struct

average(records,reccount,quiz1offset);


double average(struct studentData *record, int reccount, int offset)
{
double  sum,avg;
int k;
        // calculate the score sums
        for (k=0; k<reccount; k++)
        {
            sum += *(int *)((int)(record+k) + offset);
            //equivalent form is sum += *(int *)((int)&record[k] + offset);
        }
        avg = sum/reccount;

return avg;   
}