Output

Hey guys, I have this easy program and my algorithm looks right for the percentages, but I keep printing zeros. Can someone tell me what I'm doing wrong?


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
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main()
{
	int xxx;
	int total, *p;
	string name, *n;
	cout<<"Enter the number of total candidates: "<<endl;
	cin>>total;
	n = new string[total];
	p = new int[total];
	cout<<"\nEnter the names of the candidates followed by the votes: "<<endl;
	for(int i = 0; i < total; i++)
	{
		cin>>n[i];
		cin>>p[i];
	}
	cout<<fixed<<showpoint<<setprecision(2)<<endl;
	int totalVotes = 0;
	for(int c = 0; c < total; c++)
		totalVotes = totalVotes + p[c];
	cout<<"Candidate         Votes Received         % of Total Votes"<<endl;
	double percent;
	for(int z = 0; z < total; z++)
	{
		percent = (p[z] / totalVotes) * 100;
		cout<<left<<setw(22)<<n[z]<<setw(22)<<p[z]<<percent<<endl;
	}
	cout<<"Total                 "<<totalVotes<<endl<<endl;
	int maxIndex = 0;
	int index;
	for(index = 1; index < total; index++)
		if(p[maxIndex] < p[index])
			maxIndex = index;
	cout<<"\nThe winner of the election is "<<n[maxIndex]<<"."<<endl;
	cin>>xxx; // read output
	return 0;
}
(p[z] / totalVotes)

This will return become an integer. You will need to cast one of the parts to a double so you get double division instead of integer division.
line 30:

integer / integer gives you an integer. For example... 3 / 4. Both 3 and 4 are integers, so the result is an integer answer: 0.

If you want to get 0.75, you need to do floating point division, which means at least one of the numbers you're dividing needs to be a float/double.

OR, if you want to keep using integers, you can multiply by 100 first:

ie:

p[z] * 100 / totalVotes

EDIT: doh, too slow
Last edited on
Ah, okay. Thank you guys, I got it.
Topic archived. No new replies allowed.