1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void getPercent(int votes, int totalVotes[], double percent[]);
void printResult(int total, string lastName[], int vt[], double percent[]);
int winInd(int vt[]);
const int CNDTS = 5;
int main()
{
string lastName[CNDTS];
int votes[CNDTS] = { 0 };
int totalVotes = 0;
double percent[CNDTS] = { 0.0 };
for (int i = 0; i < CNDTS; i++)
{
cout << "Candidate Votes Received % of Total Votes" << endl;
cout << "candidate " << (i+ 1) << "votes received: ";
cin >> lastName[i] >> votes[i];
totalVotes += votes[i];
}
getPercent(totalVotes, votes, percent);
printResult(totalVotes, lastName, votes, percent);
system("pause");
return 0;
}
//function to print the result
void printResult(int total, string lastName[], int votesTotal[], double percent[])
{
cout << "Candidate Votes Received % of Total Votes\n";
for (int i = 0; i < CNDTS; i++)
{
cout << left << setw(10) << lastName[i] //creates the output grid
<< right << setw(15) << votesTotal[i]
<< right << setw(15) << percent[i] << setprecision(4) << showpoint
<< "\n";
}
cout << "Total " << total << "\n"; // It obtains the total from the main function (line 24 on main)
cout << "The Winner of the Election is " << lastName[winInd(votesTotal)];
}
int winInd(int votesTotal[])
{
int largest = 0;
int position = 0;
for (int i = 0; i < CNDTS; i++)
{
// If it finds the largest value, then record the larfest variable
// and record its position by recording the index.
if (votesTotal[i] > largest) //will find the largest sum
{
largest = votesTotal[i];
position = i;
}
}
return position; // Return the index of the largest value.
}
//function to calculate the percentages
void getPercent(int votes, int totalVotes[], double percent[])
{
for (int i = 0; i < CNDTS; i++)
{ //Forumla to find the percent
percent[i] = static_cast<double>(totalVotes[i]) / static_cast<double>(votes) * 100;
}
}
| |