c - 将 +/- 字母等级定义为常量。 C

标签 c arrays constants c-preprocessor

我正在尝试完成一个实验,其中我必须根据结构链接列表中给出的类(class)信息计算总平均绩点 (GPA)。我试图用适当的成绩点来定义每个字母等级(“A”= 4.0,“A-”= 3.7 ...)。类(class)成绩存储在字符数组中。我可以使用 #define 导数来定义字母等级 A、B、C、D、E,但在定义 +/- 等级时遇到困难。使用 #define 导数是完成此任务的正确方法吗?如果是这样,有人能够向我展示正确的语法吗?

/* Definition of a data node holding course information */
  struct course {
    int term;
    char name[15];
    char abbrev[20];
    float hours;
    char grade [4];
    char type[12];
    struct course *next;
  };



float gpa ( struct course *ptr )
{
  float totalhours;
  float gpa;
  float gradepoints;

  while (ptr != NULL )
    {
      totalhours += (ptr->hours);
      gradepoints = (ptr->hours * ptr->grade);
    }
  gpa = (gradepoints / totalhours);
}

最佳答案

您正在寻找的是映射或字典,C 本身不支持它们。您可以为您的用例实现一个简单的映射作为 struct 数组,如下所示:

struct GradeInfo {
  char *grade;
  float value;
};
struct GradeInfo GRADES[] = { {"A", 4.0}, {"A-", 3.7}, ..., {NULL, 0.0}};

然后在 for 循环中循环这个数组(修复更多错误):

float gpa ( struct course *ptr )
{
  float totalhours = 0.0;
  float gradepoints = 0.0;

  for (; ptr; ptr = ptr->next)
    {
      float grade = -1.0;
      struct GradeInfo *info;
      for (info = GRADES; info->grade; ++info) {
        if (!strcmp(ptr->grade, info->grade)) {
          grade = info->value;
          break;
        }
      }
      if (grade < 0) {
        continue;
      }
      totalhours += (ptr->hours);
      gradepoints = (ptr->hours * ptr->grade);
    }
  if (!totalhours) {
    return 0.0;
  }
  return (gradepoints / totalhours);
}

关于c - 将 +/- 字母等级定义为常量。 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12666167/

相关文章:

c - c 中具有整数的表的 union 合并

c - 用 ALSA 录音

c - Shift + Enter 与在控制台中输入

arrays - 在 Ruby 中将数组破坏性地转换为数组

arrays - Powershell字节数组到十六进制

c - 将语言编译为 C 是个好主意吗?

c++ - 关于 C++ OOP 数组成员复制行为

php - 使用包含常量名称的简单变量访问类常量

c++ - 同时使用 const 和 non-const 进行参数传递

c - 是否可以在运行时在 C 中定义常量?