0

I am working on problem set 3 runoff and I am having trouble with getting my print_winner function to work correctly. When I run the program it basically does nothing and quits the program. It gets all the voters inputs but doesn't print out a winner if the candidate is above 50% like it should. It's possible I have errors in the function I wrote to sort the candidates out so I'll include that code as well. Please Help? I've run my program through check50 so I know my tabulate function isn't the problem but I can't figure it out. Feel free to give me any other pointers as well I'm still very new to coding.

PRINT_WINNER CODE

// Print the winner of the election, if there is one
bool print_winner(void)
{
    sort_candidates();
    int c3 = 0;
    //for loop to go through candidates
    for(int x = 0; x < candidate_count; x++)
    //if winning candidate has more than 50% of vote
   {
        if (candidates[x].votes >= (voter_count / 2))
    //print name to stdout
        {
            printf("%s", candidates[x].name);
            c3++;
        }

   }

    if (c3 > 0)
    {
        return false;
    }
    else return true;
}

SORTING FUNCTION

// sorting function
void sort_candidates(void)
{
    // sort the numbers
        for (int u = 0; u < candidate_count; u++)
        {
            int c2 = 0;
            if (candidates[u].votes > candidates[u+1].votes)
            {
                candidate ph2;
                ph2 = candidates[u + 1];
                candidates[u + 1] = candidates[u];
                candidates[u] = ph2;
                c2++;
            }
            if (c2 > 0)
            {
                sort_candidates();
            }
        }
}

1 Answer 1

0

I just finished this assignment successfully with a lot of effort! Looks like you created a custom function to sort, which is not needed. Here's how I did it:

  1. count the total votes of all remaining candidates
  2. if any of the remaining candidates have more than total votes / 2 + 1, they are the winner ** in both steps, only consider remaining candidates

Good luck!

You must log in to answer this question.

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