[英]CS50 pset3 plurality program doesn't print_winner function (did not print both winners of election)
[英]CS50 pset3: Plurality. Print_winner function incorrectly printing multiple candidates regardless of input when running the program
CS50 的 pset3 复数要求您根据他们获得的票数打印“选举”的获胜者。 投票由用户输入。
在我必须打印获胜者之前,我的程序运行良好。 我已经尝试了几天尝试不同的方法,但无法理解它。
无论输入如何,我的代码当前都会输出多个候选者。 我猜变量“most_votes”和“election_winner”保留了代码顶部的分配值。
如果多个候选人获得相同数量的选票,如果他们获得最多票数和多个获胜者,我该如何重写它以打印单个获胜者?
谢谢你的帮助!
这是我的代码:
// Print the winner (or winners) of the election
void print_winner(void)
{
int most_votes = candidates[0].votes;
string election_winner = candidates[0].name;
// Loop over each candidate
for (int i = 1; i < candidate_count; i++)
{
// Count how many votes each candidate received and determine who
// received the most votes
if (most_votes < candidates[i].votes)
{
most_votes = candidates[i].votes;
election_winner = candidates[i].name;
}
}
// Loop over candidates a second time
for (int j = 1; j < candidate_count; j++)
{
// Count how many votes each candidate received
// Compare number of votes of each candidate
// Check if mutiple candidates have the most votes
if (most_votes == candidates[j].votes && election_winner != candidates[j].name)
{
// Print all candidates with the most votes
printf("%s\n", candidates[j].name);
}
}
// Print the name of winner with most votes
printf("%s\n", election_winner);
return;
}
如果可以有多个获胜者,您不需要(也不应该拥有)变量election_winner
。
most_votes
的值。most_votes
,那么您就知道候选人是赢家,您可以将姓名打印出来,或者其他任何需要的内容。感谢您的帮助,我能够弄清楚。 将其简化为@vmt 建议并有效!
将变量“most_votes”更改为“0”而不是“candidates[0].votes”可以更容易理解。
// Print the winner (or winners) of the election
void print_winner(void)
{
int most_votes = 0;
// Loop over each candidate
for (int i = 0; i < candidate_count; i++)
{
// Count which candidate has the most votes and assign them most_votes
if (most_votes < candidates[i].votes)
{
most_votes = candidates[i].votes;
}
}
// Loop again over candidates
for (int j = 0; j < candidate_count; j++)
{
// Check if mutiple candidates have the most votes
if (most_votes == candidates[j].votes)
{
// Print all candidates with the most votes
printf("%s\n", candidates[j].name);
}
}
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.