我已经完成了cs50的pset3的复数程序,但是在我的代码上运行check50时,我收到了针对print_winner函数的以下错误:
:) plurality.c exists
:) plurality compiles
:) vote returns true when given name of first candidate
:) vote returns true when given name of middle candidate
:) vote returns true when given name of last candidate
:) vote returns false when given name of invalid candidate
:) vote produces correct counts when all votes are zero
:) vote produces correct counts after some have already voted
:) vote leaves vote counts unchanged when voting for invalid candidate
:) print_winner identifies Alice as winner of election
:) print_winner identifies Bob as winner of election
:) print_winner identifies Charlie as winner of election
:( print_winner prints multiple winners in case of tie
print_winner function did not print both winners of election
:) print_winner prints all names when all candidates are tied
即使我的函数确实在出现平局的情况下会打印出多个获胜者(并且我在各种情况下都对其进行了多次测试),但该错误仍然持续存在,我不确定为什么。有人可以在下面检查我的代码,并详细说明代码有什么问题吗? (很抱歉,如果它太乱/效率低下,我花了一段时间来写,因为花了我一段时间才弄清楚如何打印多个获奖者):
void print_winner(void)
{
int j = 0;
int max = candidates[0].votes;
int competitor;
int competitor2;
string winner = candidates[0].name;
// loop over all candidates + determine candidate with most votes (max)
// + name candidate with most votes (winner)
for (j = 1; j < candidate_count; j++)
{
competitor = candidates[j].votes;
if (max < competitor)
{
max = competitor;
winner = candidates[j].name;
}
}
// loop over candidates again to determine if multiple winners + print winner/winners
for (int f = 0; f < candidate_count; f++)
{
competitor2 = candidates[f].votes;
if (max == competitor2 && candidates[f].name != winner)
{
for (int i = 0; i < candidate_count; i++)
{
printf("%s\n", candidates[i].name);
}
return;
}
}
printf("%s\n", winner);
return;
}
编辑:正如DinoCoderSaurus指出的那样,我的i
循环是有问题的。我意识到甚至没有必要,因为我的f
循环已经具有相同的功能。下面,我删除了i
循环,对f
循环进行了一些修改,并将printf("%s\n", winner);
行移到f
循环之前,因此,如果有多个获胜者,他们按正确的顺序打印:
void print_winner(void)
{
int j = 0;
int max = candidates[0].votes;
int competitor;
int competitor2;
string winner = candidates[0].name;
// loop over all candidates + determine candidate with most votes (max)
// + name candidate with most votes (winner)
for (j = 1; j < candidate_count; j++)
{
competitor = candidates[j].votes;
if (max < competitor)
{
max = competitor;
winner = candidates[j].name;
}
}
printf("%s\n", winner);
// loop over candidates again to determine if multiple winners + print winner/winners
for (int f = 0; f < candidate_count; f++)
{
competitor2 = candidates[f].votes;
if (max == competitor2 && candidates[f].name != winner)
{
printf("%s\n", candidates[f].name);
}
}
return;
}
答案 0 :(得分:1)
尝试这次选举:3位候选人:a,b,c。五位投票者:a,a,b,b,c。
预期输出是多少?程序输出什么?
问题出在SELECT ca.syear, COUNT(cc.joined),cc.joined
FROM schedules AS cc JOIN
schedule_assignment AS ca
ON ca.idx = cc.assignment
where student = 1 AND cc.joined = 1
GROUP BY ca.syear;
循环中。如果发现“第二名”获胜者,将打印哪些候选人名称?