Home > OS >  The check50 command returns an error for my print_winner function
The check50 command returns an error for my print_winner function

Time:01-01

The print_winner function must find the candidate who has the highest votes and print its name. In case there are more than 1 who have the same number of votes, the function must print their names. here is the error

:) 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

mycode

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;
}

CodePudding user response:

You are "switching" the number of votes. The names remain the same. (And the final print always prints candidate[0].name, which is always the first candidate entered at the command line).

Give your solution some more thought. It needs to answer 2 questions. How much is the most number of votes? Which candidate(s) has that number of votes? It can be accomplished with two loops through the candidates. Good luck.

CodePudding user response:

so the code should be like this

// 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\n", candidates[j].name);
        }
    return;
}
  • Related