了解CS50径流投票()和tabulate()函数

发布于 2025-02-05 10:26:10 字数 917 浏览 1 评论 0原文

我刚刚从CS50讲座3中解决了径流问题,但我仍然不确定投票和制表函数呼叫如何工作。 我已经尝试分解该功能,但我了解了其中的60%,但仍然不确定。 就像2D阵列在候选人类中链接或工作的部分一样。选民和等级变量如何用于首选项数组?为什么要分配我而不是将1递增为投票或偏好[i] [j]。

如果可能的话,有人可以将其分解给我吗?

我真的很感激。

// Record preference if vote is valid
bool vote(int voter, int rank, string name)
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(candidates[i].name, name) == 0)
        {
            preferences[voter][rank] = i;
            return true;
        }
    }
    return false;
}

// Tabulate votes for non-eliminated candidates
void tabulate(void)
{
    for (int i = 0; i < voter_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            int vote = preferences[i][j];
            if (!candidates[vote].eliminated)
            {
                candidates[vote].votes += 1;
                break;
            }
        }
    }
    return;
}

I just did the runoff problem from cs50 lecture 3 But i m still not quite sure how the vote and tabulate function calls are working.
i've tried breaking down the function in parts and i understood around 60% of it but still not sure.
Like the parts where the 2D array is linking or working under the candidates class. how does the voter and rank variables work for preferences array? why assign them i instead of increment 1 to the votes or preferences[i][j].

can someone please break it down to me if possible?

i'd really appreciate it.

// Record preference if vote is valid
bool vote(int voter, int rank, string name)
{
    for (int i = 0; i < candidate_count; i++)
    {
        if (strcmp(candidates[i].name, name) == 0)
        {
            preferences[voter][rank] = i;
            return true;
        }
    }
    return false;
}

// Tabulate votes for non-eliminated candidates
void tabulate(void)
{
    for (int i = 0; i < voter_count; i++)
    {
        for (int j = 0; j < candidate_count; j++)
        {
            int vote = preferences[i][j];
            if (!candidates[vote].eliminated)
            {
                candidates[vote].votes += 1;
                break;
            }
        }
    }
    return;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文