首页 > 解决方案 > 为什么没有打印出最多选票的“候选人”?

问题描述

bool print_winner(void)
{
    int others = 0;
    
    for (int i = 0; i < candidate_count; i++)
    {
       int h = others < candidate_count;
       
       if(candidates[i].votes > candidates[h].votes
       {
           printf("%s\n", candidates[i].name);
           return true;
       }
    }
    return false;
} ``

我想要在函数中做的是打印得票最多(多数)的候选人的姓名。但是,当我编译程序时,什么都不会打印。 我还创建了这个函数来“消除”候选人,所以错误可能来自那里:

    void tabulate(void)
    {
        int others = 0;
    
            for(int i = 0; i<candidate_count; i++)
            {
              int h = others < candidate_count;
          
              if(candidates[i].votes < candidates[h].votes)
              {
                  //eliminate candidates[i].votes
                  candidates[i].eliminated = true;
              
              }
            } 
        return;
   }

*当我编译我的程序时,似乎没有任何问题。

标签: c

解决方案


您需要循环所有候选人并保留获胜者的数组索引例如

void print_winner(void)
{
    int winner = 0;
    if (!candidate_count)
        return;
    for (int i = 1; i < candidate_count; i++)
    {       
       if(candidates[i].votes > candidates[winner].votes) {
           winner = i;
       }
    }
    printf("The winner is %s\n", candidates[winner].name);
} 

推荐阅读