CS50 Pset3多元化-无法将第二位候选人显示为获胜者

时间:2020-09-14 15:35:12

标签: cs50

即使是平局,该代码也能正常工作。例如。候选人A,B,C,如果A获得2票而B获得2票,则将打印A和B。

如果C得票最多,它也会打印C。但是当B得票最多时,它只会继续打印A。有人可以帮忙吗?预先感谢!

检查50条消息,如下所示:

:) print_winner将爱丽丝确定为选举获胜者

:( print_winner标识鲍勃为选举获胜者

原因 print_winner函数未打印出选举的获胜者

:) print_winner将查理确定为选举获胜者

:) print_winner在出现平局的情况下打印多个获胜者

:) print_winner会在所有候选项均被捆绑时打印所有名称

#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Max number of candidates
#define MAX 9

// Candidates have name and vote count
typedef struct
{
    string name;
    int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;

// Function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }

    int voter_count = get_int("Number of voters: ");

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name))
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();
}

// Update vote totals given a new vote
bool vote(string name)
{
    for(int a = 0; a < candidate_count; a++)
    {
        if(strcmp(name, candidates[a].name) == 0)
        {
            candidates[a].votes++;
            printf("%i\n", candidates[a].votes);
            return true;
        }
    }
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    int winner_votes;
    for(int a = 1; a < candidate_count; a++)
    {
        if(candidates[a].votes <= candidates[0].votes)
        {
            winner_votes = candidates[0].votes;
        }
        else
        {
            winner_votes = candidates[a].votes;
        }
    }
    for (int b = 0; b < candidate_count; b++)
    {
        if(candidates[b].votes == winner_votes)
        {
            printf("%s\n", candidates[b].name);
        }
    }
    return;
}

1 个答案:

答案 0 :(得分:0)

if(candidates[a].votes <= candidates[0].votes)在选举中是个问题,爱丽丝获得1票,鲍勃获得2票,查理获得1票。当a = 2时,winner_votes将被设置为1。该比较不能基于任何特定候选人的票数(即candidates[0]),而是基于“当前” winner_votes