Write a program that allows the user to enter the last names of five candidates in a local election and the number of votes received by each candidate. The program should output each candidate's name, the number of votes received, and the percentage of the total votes received by the candidate. Your program should also output the winner of the election. A sample output is:
Candidate Votes Received % of Total Votes
Johnson 5000 25.91
Miller 4000 20.73
Duffy 6000 31.09
Robinson 2500 12.95
Ashtony 1800 9.33
Total 19300
ANd this is what I got so far,
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
I am going to show where you went wrong, what are the advantages of having really short name, and why it is not the good idea to get ahead of the line. Also, remember - if you want to win the election - register soon, because it sucks to be the last.
1 2 3 4 5 6 7 8 9 10 11 12
char candidate [500]; // Declare space for ONE name of up to 500 characters in length
int votes_recieved [15]; // Declare space for number of votes for 15 candidates
double vote_percentage [25];// Declare space for percentage score for 25 candidates
for (int i=0; i<20; i++)
{
// Ask for 20 names and 20 scores.
// But votes_received has only 15 elements!
// it won't hold score for candidates indexed 15-19
// And candidate[i] can only store one letter, not one name!
cin >> candidate [i] >> votes_recieved [i];
}
1 2 3 4 5 6 7 8 9 10 11
// There was a Tsunami, so nobody went to election.
// Total sum of votes = 0
for (int i=0; i<15; i++) // (<== Poor canditades 15-19
// nobody's keeping their score anyway!)
{
vote_percentage [i] = (votes_recieved [i]/sum);
// Ooops! Divides by zero. ^
// Suddenly, the Tsunami is /|\
// just a nuisance... |
// The world just ended! |
}
1 2 3 4 5 6 7 8 9 10 11
double max = vote_percentage [0]; // Sucks to be the first guy
for (int i=1; i<15; i++)
{
if (vote_percentage [i] > max) // he never gets to be
{ // the winer, since his
max = vote_percentage [i]; // score will never be better
index = i; // than his score... what a zero he is
// Guys 15 - 19 don't
// get their chance either.
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13
cout << setw(4) << "Candidate" << " Votes Received" << " % of Total Votes" << endl;
for (int i=0; i < 20; i++)
{
// One letter |
// only \|/
// '
// /-----------\
cout << setw(5) << candidate [i] << votes_recieved [i] << vote_percentage [i] << endl;
// \________________/ \_________________/
// This one was never ^ ^
// evaluated for candidates /|\ ...and neither /|\
// indexed 15-19... | was this |
}