【问题标题】:The check50 command returns an error for my print_winner functioncheck50 命令为我的 print_winner 函数返回错误
【发布时间】:2023-01-01 05:45:39
【问题描述】:

print_winner 函数必须找到得票最高的候选人并打印其姓名。如果有超过 1 个拥有相同票数的人,该函数必须打印他们的名字。 这是错误

:) print_winner identifies Alice as winner of election
:) print_winner identifies Bob as winner of election
:( print_winner identifies Charlie as winner of election
    print_winner function did not print winner of election
:) print_winner prints multiple winners in case of tie
:) print_winner prints all names when all candidates are tied

我的代码

void print_winner(void)
{
    int lenght = sizeof(candidates[0].votes);
    for (int i = 1; i < lenght - 1 ; i++)
    {
        if (candidates[0].votes <= candidates[i].votes)
        {
            candidates[0].votes = candidates[i].votes;
        }
        if (candidates[0].votes == candidates[i].votes)
        {
            printf("%s\n", candidates[i].name);
        }
    }
    printf("%s\n", candidates[0].name);
    return;
}

【问题讨论】:

  • 什么是candidates?什么是candidates[0]?什么是candidates[0].votes?请创建一个minimal reproducible example给我们看。
  • 对于一般的计数,在你完成之前你不能真正显示结果全部要计算的元素。您不能在循环中间声明“赢家”。
  • 一切正常,但如果有 2 个候选人 a、b 和 3 票 b、b、无效投票 \\ 它应该打印 b 但它打印 b a
  • 请提供足够的代码,以便其他人可以更好地理解或重现问题。

标签: c for-loop printf cs50


【解决方案1】:

您正在“切换”票数。名称保持不变。 (和最后的打印总是打印 candidate[0].name,即总是第一个候选人在命令行输入)。

再考虑一下您的解决方案。它需要回答2个问题。最多的票数是多少?哪位候选人有那么多票?它可以通过候选人的两个循环来完成。祝你好运。

【讨论】:

    【解决方案2】:

    所以代码应该是这样的

    // Print the winner (or winners) of the election
    void print_winner(void)
    {
        int lenght = sizeof(candidates[0].votes);
        int max_votes = 0;
        for (int i = 0 ; i < lenght ; i++)
        {
            if (candidates[i].votes > max_votes)
            {
                max_votes = candidates[i].votes;
            }
        }
        for (int j = 0 ; j < lenght ; j++)
            if (candidates[j].votes == max_votes)
            {
                printf("%s
    ", candidates[j].name);
            }
        return;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-14
      • 2022-07-30
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      • 2022-08-21
      • 1970-01-01
      • 2021-01-18
      相关资源
      最近更新 更多