I am writing a program that outputs an election and the votes that each person gets. The candidates are entered into the program and it outputs the candidate names and the amount of votes that each person gets. I am trying to calculate the percentage of votes each candidate gets but am not sure how to go about doing it so I am having trouble with it, and could use some help.
#include<iostream>
#include<iomanip>
usingnamespace std;
int main()
{
//varaible declarations
string *names;
double *votes;
int n;
//prompt and read the number of candidates
cout << "Enter number of candidates: ";
cin >> n;
//create two dynamic arrays
names = new string[n];
votes = newdouble[n];
double sum = 0;
double winner = -1;
string winnerName = "";
int total = 0;
//run a loop to read the candidate details
for(int i = 0; i < n; i++) {
//prompt and read candidates name
cout << "Enter candidate's name: ";
cin >> names[i];
//prompt and read number of votes received
cout << "Enter votes received: ";
cin >> votes[i];
//compute the running total of number of votes
sum += votes[i];
//compare and get the winner
if(winner < votes[i]) {
winner = votes[i];
winnerName = names[i];
}
}
cout << endl;
cout << setprecision(2) << fixed;
//display the output headers
cout << setw(20) << left << "Name" << setw(20) << left << "Votes" << setw(20) << left << "% of Total Votes" << endl;
//iterate and display the candidate details
for(int i = 0; i < n; i++) {
cout << setw(20) << left << names[i] << setw(20) << left << setprecision(0) << votes[i] << setprecision(2) << votes[i]/sum*100 << endl;
total += votes[i];
}
//displat the total number of votes
cout << setw(20) << left << "Total" << setw(20) << left << total << endl;
//display the winner
cout << endl << "The winner of the Election is " << winnerName;
return 0;
}
$ ./a.out
Enter number of candidates: 4
Enter candidate's name: Fred
Enter votes received: 20
Enter candidate's name: Barney
Enter votes received: 30
Enter candidate's name: Wilma
Enter votes received: 40
Enter candidate's name: Betty
Enter votes received: 50
Name Votes % of Total Votes
Fred 20 14.29
Barney 30 21.43
Wilma 40 28.57
Betty 50 35.71
Total 140
The winner of the Election is Betty
Apart from the fact that you leak the memory you new[] on lines 18,19.