C ++输出数组中的最高元素

时间:2018-08-20 18:11:53

标签: c++ arrays element

当试图遍历数组以获取最高计数而不是最高计数时,我试图让程序在候选竞赛中输出获胜者,而从零开始获取最高计数,我觉得我已经尝试了所有方法。 我一直在尝试尝试在寻找赢家功能中进行更改,但似乎没有任何反应,我看不到我在做什么错,请帮忙。

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>

using namespace std;

//User inputs data for candidates and votes.
//Output Candidates, votes, and percentage.
//Names that will be used are johnson, miller, duffy, robinson, ashtony
//count of votes to use = 5000, 4000, 6000, 2500, 1800, total 19300
//Percentages that will be used for candidates= 25.91, 20.73, 31.09, 12.95, 9.33

int findWinner(int votes[]);
void Results(string candidates[], int votes[]);
double Percentage(int votes[], int vote);
int tester[5] = {};
const int NUMBER_OF_CANDIDATES = 5;

int main()
{

   string candidates[NUMBER_OF_CANDIDATES];
   int votes[NUMBER_OF_CANDIDATES];

   cout << "Enter 5 Candidates with their votes ex: DelBosque 7000: ";
   for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
      cin >> candidates[i] >> votes[i];

   }
   cout << "Candidate  Votes Received  % of Total Votes" << endl;
   Results(candidates, votes);

   cout << "The Winner of the Election is " << candidates[findWinner(votes)] <<  
      endl;

   return 0;
}

double Percentage(int votes[], int vote){
   int sumOfVotes = 0;

   for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
      sumOfVotes += votes[i];
   }

   double percent = static_cast<double>(vote) / sumOfVotes;
   double votePercent = 0;
   votePercent = percent * 100;
   std::cout << std:: fixed;
   std::cout << std:: setprecision(2);
   std::cout << votePercent;

   return 0;
};


void Results(string candidates[], int votes[]){

   for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
      cout << candidates[i] << setw(15) << votes[i] << setw(15);
      int percent = Percentage(votes, votes[i]);
      cout << percent << "%" << endl;
   };
};

// You are returning the number of votes. Shouldn't you be returning the 
// index referenced by the highest number of votes?

int findWinner(int votes[]){
   int index = 0;
   int winner = 0;    
   for (int i = 0; i < NUMBER_OF_CANDIDATES; i++) {
      if (votes[i] > winner)               
         winner = votes[i];  
      index = i;  


   };
   return index;
};

1 个答案:

答案 0 :(得分:3)

if条件下,您需要以下两行。

  winner = votes[i];  
  index = i;  

喜欢:

  if (votes[i] > winner)               
  {
     winner = votes[i];  
     index = i;  
  }

您拥有的等同于:

  if (votes[i] > winner)               
  {
     winner = votes[i];  
  }
  index = i;  

这是不正确的。