I need some help with arrays.

I'm making a program where a user inputs candidates names and the amount of votes received. Then I want to output the candidates names, the number of votes, and the percentage of the votes each received. It seems I'm having an issue when I try to use the function to calculate the percentages.

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

using namespace std;

float percent(int[], int);

int main(int argc, char *argv[])
{
    const int CANDIDATES = 5;
    int votes[CANDIDATES], win;
    string dudes[CANDIDATES];
    
    for(int x = 0; x < CANDIDATES; ++x)
    {
        cout << " Enter the name of the candidate " << endl;
        cin  >> dudes[x];
        
        cout << " Enter the amount of votes recieved " << endl;
        cin  >> votes[x];   
    }
    
    system("CLS");
    
    cout << left << setw(8) << " Candidate " << right << setw(8) << " Votes "  
         << " % of votes " << endl;
         
    for(int x = 0; x < CANDIDATES; ++x) 
    {
        cout << left << setw(8) << dudes[x] << right << setw(8) << votes[x]  
             << percent(votes, CANDIDATES) << endl;
    }
    
    
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

float percent(int total[], int element)
{
    float percent;  
    
    for(int x = 0; x < element; ++x)
    {
        float percent = 0;    
        percent = (total[x]*100)/38600;
    }
    
    return percent;
}
The percent function iterates through each candidate every time it's called. The final result of percent will be for the fifth candidate - that's the value that's returned to main.

Instead of having a for loop in the function, perhaps just send the element of the array for the current candidate (not the whole array) and calculate the percentage for that one candidate.
In line 48, you are always resetting the value of percent. So at the end of the loop, you end up getting and returning only the value of the 5th candidate.

Aceix.
Topic archived. No new replies allowed.