首页 > 解决方案 > 在 C 中运行时创建变量名

问题描述

我想知道是否有人可以帮助我?我有以下保存学生科目成绩的基本结构:

typedef struct student{
   char name[25];
   int  maths, 
        science, 
        english, 
        age;  
} student; 

我创建了一个这种类型的数组并填充了数据。我写了 3 个函数来计算每个科目的最高和最低分数。这些功能几乎相同,但唯一的区别是他们正在研究的主题,例如计算数学的最低/最高分数

void highestAndLowestMaths(student s1[]){  

   int highest = s1[0].maths, highestPos = 0,
       lowest  = s1[0].maths, lowestPos  = 0; 

   for( int x = 1; x < MAX_RECS; x++ ){
      if( s1[x].maths > highest ){
         highest    = s1[x].maths;
         highestPos = x;
      }
      if( s1[x].maths < lowest ){
         lowest    = s1[x].maths;
         lowestPos = x;
      }      
   }
   // then display details of highest/lowest in maths etc..
   

科学和英语的其他 2 个函数是相同的,唯一需要更改的代码部分是 s1[x]。数学到 s1[x]。科学和 s1[x]。分别是英文

因此,与其编写 3 个独立且几乎相同的函数,不如通过更改 s1[x] 来实现。数学/科学/英语部分的代码,是否会根据传递的另一个参数而更新?

我最接近解决这个问题的方法是发送一个 char 数组:

void allHighestLowest(student s1[], char subject[]){
   
   int highest = -1,  highestPos = 0, 
       lowest  = 101, lowestPos  = 0, 
       option;

   if(strcmp(subject, "MATHS") == 0){
      option = 0;      
   } else if(strcmp(subject, "SCIENCE") == 0){
      option = 1;      
   } else if( strcmp(subject, "ENGLISH" ) == 0){
      option = 2;      
   } else {
      printf("Invalid subject:\t[%s]\nExiting...\n", subject); 
      exit(1);
   }

   int member[3]; 

   for(int x = 0; x < MAX_RECS; x++){
      
      member[0] = s1[x].maths;
      member[1] = s1[x].science;
      member[2] = s1[x].english;
      
      if(member[option] > highest){
         highest    = member[option];
         highestPos = x;
      }

      if(member[option] < lowest){
         lowest    = member[option];
         lowestPos = x;
      }      
   }
   // then display details of highest/lowest in chosen subject etc..

虽然它有效,但我确信必须有更好的方法在运行时动态创建s1[x].maths/science/english的代码行,而不是使用临时数组来获取如上所示的值?结构本身可能会更改并添加更多成员,因此我正在寻找最佳解决方案,而不是复制函数和代码。

谁能指出我正确的方向?提前致谢!

标签: c

解决方案


这是在 C 中根本无法正常工作的那种东西。C 语言旨在用于低级编程,而不是高级数据抽象。

你可以这样做:

enum subject { MATH, SCIENCE, ENGLISH };

typedef struct student{
   char name[25];
   int  subject[3];
   int  age;  
} student; 

然后是这样的:

void highestAndLowest(student s1[], enum subject s){  

   int highest = s1[0].subject[s], 
       lowest = highest,           // Removed code duplication
       highestPos = 0,
       lowestPos  = 0; 

   for( int x = 1; x < MAX_RECS; x++ ){
      if( s1[x].subject[s] > highest ){
         highest    = s1[x].subject[s];
         highestPos = x;
      }
      if( s1[x].subject[s] < lowest ){
         lowest    = s1[x].subject[s];
         lowestPos = x;
      }      
   }

   ...

如果你想像在 Python 中一样简洁地做到这一点,那么编写 Python 代码。


推荐阅读