CS50 Tideman代码完全通过了check50,但未正确打印获胜者

时间:2020-05-17 10:18:03

标签: c cs50

我刚刚“完成”了潮人,尽管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

a

b

c

等级1:a

等级2:b

等级3:c

a

b

c

有什么主意为什么check50不会让我失望,以及我在代码中做错了什么导致每次投票后都会打印,而实际上并没有打印赢家?

1 个答案:

答案 0 :(得分:0)

我认为您可以采用更简单的方法。由于您要查找的只是候选对象,其锁定中的列仅具有 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;
}