In: Computer Science
1. All members may be public for this example
2. You will need three data members:
a. An array of 3 doubles to keep the votes
b. An array of 3 strings to place the candidates names
c. An array of 3 doubles to place the calculates vote
breakdown
3. You will need three methods:
a. A constructor that receives three strings and sets the names of
the candidates to these strings and set all the votes initially to
zero.
b. A "calcPercentages" method that has no arguments or return
values and simply calculates each vote percentage as one vote count
divided by the sum times 100
c. A "display Results" method that has no arguments and displays
each candidate's names and vote percentage.
source:
#include <iostream> //for
cout
#include <string> //for
string
#include <stdlib.h> //for
rand, srand
#include <time.h> //for
time
using namespace std;
//DO NOT EDIT ANY CODE ABOVE THIS LINE EXCEPT FOR LINE 12 (EDITOR'S
NAME)
class CElection
{
public:
};
//DO NOT EDIT ANY CODE BELOW THIS LINE!
int main(void)
{
//Instantiate a CElection object with three
names:
CElection TOOP("Alice","Bob","Other");
//First display a hello message
cout << "\n\n* Welcome to Decision 2019
*\n";
//Randomize the PRN
srand(time(NULL));
int vote;
for (int i=1;i<=10000;i++)
{
vote = rand()%5;
switch (vote)
{
case 0:
case 1:
TOOP.votes[0]++;
break;
case 2:
case 3:
TOOP.votes[1]++;
break;
case 4:
TOOP.votes[2]++;
}
}
TOOP.calcPercentages();
TOOP.displayResults();
}
****This requires some effort so please drop a like if you are satisfied with the solution****
I have satisfied all the requirements of the question and I'm providing the screenshots of code and output for your reference...
Code:
#include <iostream> //for cout
#include <string> //for string
#include <stdlib.h> //for rand, srand
#include <time.h> //for time
using namespace std;
class CElection
{
public:
double votes[3];
string candidateNames[3];
double votePercentages[3];
CElection(string candidate1,string
candidate2,string candidate3){
this->candidateNames[0]=candidate1;
this->candidateNames[1]=candidate2;
this->candidateNames[2]=candidate3;
for(int i=0;i<3;i++)
this->votes[i]=0;
}
void calcPercentages(){
double sum=0;
for(int i=0;i<3;i++)
sum+=this->votes[i];
for(int i=0;i<3;i++)
this->votePercentages[i]=(this->votes[i]/sum)*100;
}
void displayResults(){
for(int i=0;i<3;i++)
cout<<"\n"<<candidateNames[i]<<"
"<<votePercentages[i];
}
};
//DO NOT EDIT ANY CODE BELOW THIS LINE!
int main(void)
{
//Instantiate a CElection object with three names:
CElection TOOP("Alice","Bob","Other");
//First display a hello message
cout << "\n\n* Welcome to Decision 2019 *\n";
//Randomize the PRN
srand(time(NULL));
int vote;
for (int i=1;i<=10000;i++)
{
vote = rand()%5;
switch (vote)
{
case 0:
case 1:
TOOP.votes[0]++;
break;
case 2:
case 3:
TOOP.votes[1]++;
break;
case 4:
TOOP.votes[2]++;
}
}
TOOP.calcPercentages();
TOOP.displayResults();
}
Output Screenshot:
Code Screenshots: