You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CS50第三周Plurality程序print_winner函数无法通过check50检测

Plurality问题:本地运行正常但check50检测print_winner全失败

我多次测试Plurality代码,本地运行能正确输出获胜者(包括平局场景),但check50检测显示vote函数全部通过,print_winner函数的所有检测项均失败。

check50检测结果如下:

:) 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 function did not print winner of election
:( print_winner identifies Bob as winner of election
    print_winner function did not print winner of election
:( print_winner identifies Charlie as winner of election
    print_winner function did not print 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
    print_winner function did not print all three winners of election

我的print_winner代码如下:

// Print the winner (or winners) of the election
void print_winner(void)
{
    bool n = 0;
    for (int i = candidate_count; i > 0; i--)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            if (candidates[j].votes == i)
            {
                printf("%s\n", candidates[j].name);
                n = true;
            }
        }
        if (n == true)
        {
           break;
        }
    }

}

问题原因

你的print_winner逻辑存在致命错误:你从candidate_count开始递减遍历得票数,但候选人的实际得票数完全可能远大于候选人数(比如总投票数远多于候选人数),这时候循环根本碰不到真实的最高得票数,自然无法输出获胜者,导致check50所有相关检测失败。

修复方案

先遍历所有候选人找出最高得票数,再重新遍历候选人,输出所有得票数等于最高得票数的人:

// Print the winner (or winners) of the election
void print_winner(void)
{
    // 第一步:确定最高得票数
    int max_votes = 0;
    for (int i = 0; i < candidate_count; i++)
    {
        if (candidates[i].votes > max_votes)
        {
            max_votes = candidates[i].votes;
        }
    }

    // 第二步:输出所有得票等于最高票的候选人
    for (int i = 0; i < candidate_count; i++)
    {
        if (candidates[i].votes == max_votes)
        {
            printf("%s\n", candidates[i].name);
        }
    }
}

内容的提问来源于stack exchange,提问作者3abdoh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:48:17