[英]How do I get my program to print the winners of a plurality election if there is a tie? (CS50 Pset3)
[英]CS50 plurality - unable to print if there are too many winners
在多個prblm中,我設法更新了每個候選人的投票,我的代碼可以打印一個獲勝者,但如果他們有很多獲勝者,仍然會卡住。 通過提示或線索提供幫助,而不是整個解決方案。 提前致謝。
void print_winner(void)
{
int v = 0; //maximum number of votes
string w; //winner of the election
for (int i = 0; i < candidate_count; i++)
{
if (v <= candidates[i].votes)
{
v = candidates[i].votes;
}
}
for (int j = 0; j < candidate_count; j++)
{
if (candidates[j].votes == v)
{
w = candidates[j].name;
}
}
printf("%s\n", w);
return;
}
將您的第二個for
循環更改為:
for (int j = 0; j < candidate_count; j++)
{
if (candidates[j].votes == v)
{
w = candidates[j].name;
printf("%s\n", w);
}
}
您需要將其分成兩個 for 循環,如果將它們放在一起,則第一個循環將僅通過第一個獲得超過 1 票的候選人運行並打印。 因為它沒有檢查其他人。 該循環必須完成並遍歷整個集合才能實際找到最大票數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.