簡體   English   中英

將結構字段傳遞給C中的函數

[英]Passing Struct Field to a function in C

我有一個結構,希望將其字段傳遞給特定函數。 例如,我結構中的一個字段是學生測驗成績quiz1,即“ quiz1”。 我想計算所有測驗的平均值,最大值和最小值。我想為每次計算創建一個函數,但我不知道如何將結構的特定字段傳遞給給定函數。 這是我所擁有的:

結構:

 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變量保存該結構的記錄數。 但是,如您所見,平均功能僅針對期末考試成績。 我如何做到這一點,以便我可以傳遞結構中的任何字段並獲取其平均值。 現在,我對每個領域都有一個平均函數,這對我來說確實是一個糟糕的方法。

您的數據結構並非旨在支持您要進行的計算。 您需要重新設計您的結構。 如果要添加測驗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);

就像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;   
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM