繁体   English   中英

Tideman 中的投票功能(CS50 的 pset 3)

[英]Vote function in Tideman (pset 3 of CS50)

我正在尝试处理投票功能,有两个问题我想寻求您的帮助:

  1. 在投票函数定义中,我们有:
bool vote(int rank, string name, int ranks[])

我不明白 rank 参数的用途以及为什么在此处声明?

  1. 我对投票功能的解决方案如下:
// Update ranks given a new vote
bool vote(int rank, string name, int ranks[])
{
    for (int j = 0; j < candidate_count; j++)
    {
        for (int k = 0; k < candidate_count; k++)
        {
            //Compare the name provided by the user with the name of the candidates numbered jth in the array candidates[MAX] which already populated above
            if (strcmp(name, candidates[k]) == 0)
            {
                ranks[j] = k;
                printf("ranks[%d] = %d\n", j, k);
                }
        }
        return true;
    }
    return false;
}

printf 函数的结果如下(候选人 = {a,b,c},voter_count = 2):

等级1:a,等级[0] = 0; 等级2:b,等级[0] = 1; 等级3:c,等级[0] = 2; 等级1:c,等级[0] = 2; 等级2:b,等级[0] = 1; 等级3:a,等级[0] = 0

ranks[j] 中 j 的值没有更新。 我该如何解决这个问题?

非常感谢你的帮助!

这是一些代码:

// Update ranks given a new vote    
bool vote(int rank, string name, int ranks[]){                      
    
    //We want to cycle through the list of candidates given
    for(int i = 0; i < candidate_count; i++){

        //If the candidate(s) in the array matches with string name, we will continue
        if(strcmp(candidates[i], name) == 0){

            //This is the tricky part to understand. Read below for answer.
            ranks[rank] = i;
            return true;
        }
    }
    
    return false;
}

int rank表示用户给定的候选人排名, int i表示候选人在candidates[]的位置。 我们想根据正确的等级更新ranks[] 这仍然很难理解,所以这里有一个例子。


我们有四位候选人:约翰、吉姆、山姆、亚历克斯

string candidates[MAX]; ,约翰在candidates[0] ,吉姆在candidates[1] ,山姆在candidates[2] ,亚历克斯在candidates[3]

假设用户投票并按以下顺序投票:

  1. 亚历克斯
  2. 约翰
  3. 吉姆
  4. 山姆

让我们在bool vote(int rank, string name, int ranks[])运行它。

  1. vote(j, name, ranks)其中j = 0姓名 = Alex ,而排名是排名[]
  2. 我们将循环名称 Alex 直到我们在candidates[MAX]找到它。
  3. Alex 在candidates[i]中找到,其中 i = 3。
  4. 我们要更新ranks[]
  5. ranks[rank] = i; 将意味着ranks[rank]等于 i,即 3。换句话说,ranks[0] 等于 Alex 在candidates[MAX]的第 i 个位置。

然后重复这个循环,直到完成所有选民的排名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM