Election Program And Arrays Problems

Ok So i got a program and i need help with the arrays in it i need the output to look like this

candidate votes recieved %votes

jon 50 %50
mike 30 %30
chris 20 %20
tom 0 %0


here is my code so far if anyone can help me i would appreciate it. ive been stuck here for a while trying to figure out what to do next. someone explain step by step so i can understand THANK YOU IN ADVANCE!


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
#include <iostream>
#include <string>
using namespace std;

void InitializeData();

int main()
{
	InitializeData();
	cout<<endl;
	system("pause");
	return 0;
	

}

void InitializeData()
{
	string array1[1000];
	int n;
	int counter;
	int votes[10000];

	cout<<"how many candidates are you counting: ";
	cin>>n;
	
	while(n<2 || n>10)
		{
				cout<<endl;
				cout<<"Please enter between 2 and 10 candidates";
				cin>>n;
		}
	

	cout<<endl<<"Please Enter Their Names:";
	cout<<endl;
	for( counter=0; counter<n; counter++)
	{
		cin>> array1[counter];
		cout<<endl;
	}
	cout<<"Enter The Amount Of Votes For Each Candidate";
	for( counter=0; counter<n; counter++)
	{
		cin>> votes[counter];
		cout<<endl;
	}
	cout<<"Your candidates are as follows"<<endl<<endl;
	for( counter=0; counter<n; counter++)
	{
		cout<<array1[counter];
		cout<<endl;
	
	
	
}

}

Hi.
You have a lot more elements in the arrays than you need - you have a maximum of 10 candiates, so the two arrays need only have 10 elements.
The only thing you have left to do is calculate the percentage of the vote each candiate has (and output the results).
If you loop through the votes array and add up the total of ALL the votes, you can then simply divide the number of votes each candiate has by the total to give the percentage. You can do this in teh loop that prints the results, unless you need to store the percentages.
Correct. The only thing you need to watch out for, though, is the precision when calculating percentages. Since you've declared votes as an array of integers, you will only get whole numbers when you divide. What you need to do will resemble this:

1
2
3
4
5
6
7
8
9
10
11
12
int totalVotes = 0;
for (counter = 0; counter < n; counter++)
{
    totalVotes += votes[counter];
}

cout << "The vote percentages are as follows:" << endl << endl;
for (counter = 0; counter < n; counter++) 
{
    cout << array1[counter] << ": " << static_cast<float>(votes[counter])/static_cast<float>(totalVotes) * 100 << endl;
}


For example, using floating-precision, 15 / 100 will be 0.15, as you'd expect, but if you don't either declare the numbers as floating-precision or cast them as above, 15 / 100 will be zero, because the answer is automatically rounded down to the next integer, which in this case is zero.
Topic archived. No new replies allowed.