【发布时间】:2020-09-14 15:35:12
【问题描述】:
即使是平局,代码也能正常工作。例如。候选人 A、B、C,如果 A 得到两票,B 得到两票,它会打印 A 和 B。
如果 C 获得最多选票,它也会打印 C。但是当 B 获得最多选票时,它只会继续打印 A。有人可以帮忙吗?提前致谢!
Check50 消息如下:
:) print_winner 将 Alice 识别为选举的获胜者
:( print_winner 将 Bob 识别为选举获胜者
原因 print_winner 函数没有打印出选举的获胜者
:) 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)
{
for(int a = 0; a < candidate_count; a++)
{
if(strcmp(name, candidates[a].name) == 0)
{
candidates[a].votes++;
printf("%i\n", candidates[a].votes);
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
int winner_votes;
for(int a = 1; a < candidate_count; a++)
{
if(candidates[a].votes <= candidates[0].votes)
{
winner_votes = candidates[0].votes;
}
else
{
winner_votes = candidates[a].votes;
}
}
for (int b = 0; b < candidate_count; b++)
{
if(candidates[b].votes == winner_votes)
{
printf("%s\n", candidates[b].name);
}
}
return;
}
【问题讨论】:
标签: cs50