CS50泰德曼“当几双并列时会打印选举的获胜者”失败

时间:2020-08-30 21:05:21

标签: c cs50

编辑: 固定!必须为(winscore winscores[11];)设置一个值,其余的代码也不错,但可能会更简洁一些。最终条件是:

for (int i = 0; i < candidate_count; i++)
    {
        if (winscores[10].score >= winscores[i].score)
        {
            printf("%s\n", candidates[winscores[i].candidate]);        
        } 
    }

现在所有检查都通过了!


我正在研究CS50 Tideman,但我的代码未通过最终检查:“ print_winner在并列配对时打印选举的获胜者”。

获胜者应该在锁定矩阵中拥有最多的false,因此我计算了false的最大金额,然后以false的降序排列。然后,我打印出false数量最多的候选者。然后,我检查是否还有更多具有相同数量false的候选人。如果有的话,我也打印这些。那应该打印出获胜者,或者如果多个候选人的false数量相同,则获胜者……至少我认为,但是它仍未通过最终检查。我不确定代码中有什么问题,因此我们将不胜感激!

typedef struct {
  int candidate;
  int score;
} winscore;

winscore winscores[11];

// Print the winner of the election
void print_winner(void) {
  // int maxscore = 0;
  // int maxscore[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

  for (int i = 0; i < candidate_count; i++) {
    for (int j = 0; j < candidate_count; j++) {
      if (locked[i][j] == false) {
        winscores[i].candidate = i;
        winscores[i].score++;
      }
    }
  }

  for (int i = 0; i < candidate_count; i++) {
    for (int j = 0; j < candidate_count; j++) {
      if (winscores[i].score < winscores[j].score) {
        winscores[10].candidate = winscores[i].candidate;
        winscores[10].score = winscores[i].score;

        winscores[i].candidate = winscores[j].candidate;
        winscores[i].score = winscores[j].score;

        winscores[j].candidate = winscores[10].candidate;
        winscores[j].score = winscores[10].score;
      }
    }
  }

  printf("%s\n", candidates[winscores[0].candidate]);

  for (int i = 0; i < 10; i++) {
    if (winscores[0].score == winscores[i].score) {
      printf("%s\n", candidates[winscores[i].candidate]);
    }
  }

  return;
}

1 个答案:

答案 0 :(得分:0)

至少这个问题:winscores[i]缺少初始化,导致winscores[i].score++;出现问题。

// winscore winscores[11];
winscore winscores[11] = { 0 };