我已经完成了 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;
}
试试这个选举:3 个候选人:a、b、c。投票的五个选民:a、a、b、b、c。
什么是预期的输出?程序给出什么输出?
问题出在i
循环中。如果找到“第二个”获胜者,将打印哪些候选人姓名?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句