【问题标题】:Vote function in Tideman (pset 3 of CS50)Tideman 中的投票功能(CS50 的 pset 3)
【发布时间】:2020-12-12 10:53:53
【问题描述】:

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

  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:一个, 排名[0] = 0

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

非常感谢您的帮助!

【问题讨论】:

    标签: c function cs50 vote


    【解决方案1】:

    这是一些代码:

    // 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[]。这仍然很难理解,所以这里是一个例子。


    我们有四个候选人:John、Jim、Sam、Alex

    string candidates[MAX]; 中,John 位于 candidates[0],Jim 位于 candidates[1],Sam 位于 candidates[2],Alex 位于 candidates[3]

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

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

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

    1. vote(j, name, ranks) 其中 j = 0name = Alexranks 是排名[]
    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 个位置。

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

    【讨论】:

    • 感谢您的回答和解释!我现在明白了:)
    猜你喜欢
    • 1970-01-01
    • 2022-06-17
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多