2015-10-04 40 views
1

我有一個結構,我想將其字段傳遞給特定的函數。例如,我的結構中的一個字段是測驗1的學生測驗成績,「測驗1」。我想計算所有測試的平均值,最大值和最小值。我想爲每個計算創建一個函數,但是我不知道如何將結構的特定字段傳遞給給定的函數。這裏是我有:將結構字段傳遞給函數C

的結構:

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

+0

對於純C,您需要傳遞一個偏移量,以便可以通過'*((int *)((char *)&record [k] + offset))'來檢索得分。如果你使用C++,你可以傳遞一個指向類成員的指針,像&studentData :: mid1 –

+1

@ YakumoRan:這個建議有一個技術術語:Yuck! –

回答

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); 
+2

優秀的答案。清潔,可讀,可維護,可擴展 - 沒有手帕的煩躁。 – clearlight

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; 
} 
+1

這是一種尷尬的過度鍛鍊方法。在這種簡單的情況下,這種方法通常表明它沒有很好的設計。 – clearlight