修复plurality选举程序print_winner函数:支持单/多胜者并精简变量
解决选举计票程序中print_winner函数的问题并优化
当前的print_winner函数仅能输出单一最高票候选人,无法处理并列最高票场景,同时可以对变量进行精简优化。需求如下:
- 唯一最高票:输出对应候选人姓名
- 并列最高票:输出所有得最高票的候选人姓名
当前完整代码
#include <cs50.h> #include <stdio.h> #include <string.h> // Max number of candidates #define MAX 9 // Candidates have name and vote count typedef struct { string name; int votes; } candidate; // Array of candidates candidate candidates[MAX]; // Number of candidates int candidate_count; // Function prototypes bool vote(string name); void print_winner(void); int main(int argc, string argv[]) { // Check for invalid usage if (argc < 2) { printf("Usage: plurality [candidate ...]\n"); return 1; } // Populate array of candidates candidate_count = argc - 1; if (candidate_count > MAX) { printf("Maximum number of candidates is %i\n", MAX); return 2; } for (int i = 0; i < candidate_count; i++) { candidates[i].name = argv[i + 1]; candidates[i].votes = 0; } int voter_count = get_int("Number of voters: "); // Loop over all voters for (int i = 0; i < voter_count; i++) { string name = get_string("Vote: "); // Check for invalid vote if (!vote(name)) { printf("Invalid vote.\n"); } } // Display winner of election print_winner(); } // Update vote totals given a new vote bool vote(string name) { // TODO for (int i = 0; i < candidate_count; i++) { if(strcmp(name, candidates[i].name) == 0) { candidates[i].votes++; return true; } } return false; } // Print the winner (or winners) of the election void print_winner(void) { int max = 0; int i; int index; for (i = 0; i < candidate_count; i++) { if (candidates[i].votes > max) { max = candidates[i].votes; index = i; } } printf("%s\n" , candidates[index].name); return; }
修改后的print_winner函数
// Print the winner (or winners) of the election void print_winner(void) { // 第一步:确定最高得票数 int max_votes = 0; for (int i = 0; i < candidate_count; i++) { if (candidates[i].votes > max_votes) { max_votes = candidates[i].votes; } } // 第二步:输出所有得票数等于最高票的候选人 for (int i = 0; i < candidate_count; i++) { if (candidates[i].votes == max_votes) { printf("%s\n", candidates[i].name); } } }
说明
- 处理并列最高票:通过两次遍历实现,第一次遍历找到最高得票数
max_votes,第二次遍历筛选出所有得票数等于max_votes的候选人并输出,完美覆盖唯一最高和并列最高两种场景。之前的实现只记录了第一个最高票候选人的索引,遗漏了后续同票的情况。 - 精简变量:
- 移除了多余的
index变量,无需记录候选人索引,直接通过条件判断输出符合要求的姓名 - 循环变量
i直接在for循环内声明,避免提前定义冗余变量,代码更简洁紧凑
- 移除了多余的
内容的提问来源于stack exchange,提问作者Abdelrhman T.Mohamed
相关产品推荐
相关产品推荐

