0

I am trying to do the Plurality exercise for problem set 3, but when I type this to test it, I get errors even though I believe my program looks correct.

check50 cs50/problems/2021/x/plurality

I get the following message:

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

This is my code. To me it looks correct, and also prints what looks correct to me when I have tested it:

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

        for (int j=0; j<candidate_count; j++)
        {
            if (candidates[j].votes==candidate_count-i)
            {
            return;
            }
        }

    }

}

1 Answer 1

1

This if (candidates[j].votes==candidate_count-i) may or may not be the winner. In an election with 3 candidates and 3 voters, a candidate can win with 3 votes. In an election with 5 candidates and 3 voters, a candidate with 3 votes will win.

In the walkthrough, Brian says:

Print the name of the candidates(s) who have the most votes.

One must know what is "the most votes" before it can be determined which candidate or candidates has "the most votes".

2
  • Thanks for your reply. I have changed my code as can been seen from the top of this screen. I believe it should be correct now? But it still gives me errors, and tells me the winner is not being printed...
    – David
    Nov 11, 2021 at 20:36
  • candidate_count - 1 is not "the most votes" except by coincidence. Function will not give the correct result for the 1st and 2nd usage examples in the spec. "The most votes" is the maximum of all the candidates[index].votes. Suggest two loops over the candidates array. One to find the max; the second to find which candidate(s) has the max. Nov 11, 2021 at 22:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .