Hello, i need help with an output. The program calculates votes for an election and the percent of each candidate and it suppose to output a winner. But i cant figure it out. If anyone can give some ideas on how to do this id appreciate it.
#include <iostream>
#include <iomanip>
#include <String>
usingnamespace std;
// Declaring the functions
int sumVotes(int list[]);
int winnerIndex(int list[]);
int votes[5];
double percent[10];
int main()
{
string name[5];
int i;
int winner;
cout << fixed << showpoint;
cout << setprecision(2);
cout << "Please enter the five candidates running and the amount of votes recieved. \n";
for(i=0; i<5; i++)// Loop to get all candidate and votes
{
cout << "\nEnter the name of the candidate and the number of votes: \n";
cin >> name[i];
cin >> votes[i];
}
//Declaring
int totalvote;
totalvote = sumVotes(votes);
int w;
w = winnerIndex(votes);
//Prints Results
cout << "\nName" << setw(25) << "Votes Receieved" << setw(20) << "% of Total \n" << endl;
for(i=0; i<5; i++)
{
percent[i] = static_cast<double>(votes[i]) / static_cast<double> (totalvote) * 100;
cout << name[i] << setw(21) << votes[i] << setw(20) << percent[i] << endl;
}
cout << endl << setw(0) << "Total Votes: " << totalvote;
cout << "\nThe winner is: " << winner << endl;
cout << "\n" << endl;
system ("pause");
return 0;
}
int sumVotes(int votes[])//Array to add votes together
{
int i;
int total = 0;
for(i=0; i<5; i++)
total = total + votes[i];
return total;
}
int winnerIndex(int votes[])//Array to declare winner
{
int i;
int maximum;
int winner = 0;
maximum = votes[0];
for(i=0; i<5; i++)
{
if(votes[i] > maximum)
winner = i;
maximum = votes[i];
}
return maximum;
}
On line 79, you are assigning i to winner, which is local to winnerIndex(). Why? Nothing is done with winner after that since you return maximum and winner is local only to the function so is destroyed once the function exits. Also, the winner variable declared in main() is of type int. It can only contain a number. Why wouldn't it output a number?