【问题标题】:CS50 Tideman code passes check50 fully but isn't printing the winner correctlyCS50 Tideman 代码完全通过 check50 但未正确打印获胜者
【发布时间】:2020-05-17 10:18:03
【问题描述】:

我刚刚“完成”了潮人,虽然 check50 通过了我,但它肯定没有正确打印获胜者。有其他人遇到过这个问题吗?

这是我的打印获胜者代码 -

// Print the winner of the election
void print_winner(void)
{
    //array of total "trues" in locked[i][j] by candidate i.e. total edges
    int sum_source[candidate_count]; 
    int source;

    for (int i = 0; i < candidate_count; i ++)
    {
        source = 0;
        for (int j = 0; j < candidate_count; j ++)
        {
            if (locked[i][j] == true)
            {   
                source ++;
            }    
        sum_source[j] = source;    
        }
        // sum_source[i] = source; I thought sum_source should come here to sum by candidate i 
        //but this causes check 50 to fail print winner when pairs tied
    }

    int max_source = sum_source[candidate_count - 1]; //sets max number of trues by candidate to last candidate

    for (int k = 0; k < candidate_count - 1; k ++)
    {
        if (sum_source[k] > max_source) //reset max_trues for higher number of trues
        {
            max_source = sum_source[k];
        }
    } 


    for (int l = 0; l < candidate_count; l ++)
    {
        if (sum_source[l] == max_source)
        {
            printf("%s\n", candidates[l]); //print all candidates with number of trues = max_source as winners
        }
    }
    return;
}

我的输出如下: 出于某种原因,它会在每次投票后打印,并且只是打印选票。 在这种情况下,正确的输出应该只是“a”,但是 check50 正在通过我。

:) print_winner 打印当一名候选人胜过所有其他候选人时的选举获胜者 :) print_winner 在某些对子打成平手时打印选举获胜者 要在浏览器中查看结果,请转到 https://submit.cs50.io/check50/26f6f9fe89617259dc60658b35957549f52a8e2a

~/pset3/tideman/ $ ./tideman a b c

选民人数:2

排名 1:a

排名 2:b

等级 3:c

一个

b

c

排名 1:a

排名 2:b

等级 3:c

一个

b

c

有什么想法为什么 check50 没有让我失望,还有我在代码中做错了什么导致每次投票后打印而不是实际打印获胜者?

【问题讨论】:

  • 提供minimal reproducible example,包括完整的要求声明。
  • 我很困惑。该代码通过了 check50 测试,但它不打印获胜者而是打印所有候选人?

标签: c cs50


【解决方案1】:

我认为您可以采用更简单的方法。因为您正在寻找的只是 locked 列中只有 false 值的候选人(没有人赢过他)。由于 c 将布尔值存储为 0 和 1,这就像说列的总和等于 0。 您可以像这样轻松测试它:

// Print the winner of the election
void print_winner(void)
{
    // Create an array of int called sum and populate it with zeroes
    int sum[candidate_count];
    for (int i = 0; i < candidate_count; i++)
    {
        sum[i] = 0;
    }
    // Take the cumsum of each column and return the winner as soon as it's 0
    for (int i = 0; i < candidate_count; i ++)
    {
        for (int j = 0; j < candidate_count; j ++)
        {
            sum[i] += locked[j][i];
        }
        if (sum[i] == 0)
        {
            printf("%s\n", candidates[i]);
            return;
        }
    }
    return;
}

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    相关资源
    最近更新 更多