简体   繁体   中英

Trouble accessing value in array of structs

I am having trouble with this code. In particular I can't seem to figure out why it is that the voteFractions() function doesn't work for me. It gets called appropriately, and all the correct parameters seem to reach the function, but I cannot get anything from "candidates[i].votes_fraction = candidates[i].votes/total;". All I ever get for candidates[i].votes_fraction is 0.00.

I tried running the program with NUMBER_OF_CANDIDATES = 1, and everything runs OK when that is the case, so I feel like I may be doing something silly, but I just can't seem to see it...

#define NUMBER_OF_CANDIDATES 10

typedef struct candidate{

    char name[20];
    int votes;
    float votes_fraction;

} candidate;


int totalVotes(candidate *candidates)
{
    int total = 0;
    for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
        total += candidates[i].votes;

    return total;
}


void voteFractions(candidate *candidates, int total, char *winner)
{
    float most_votes = 0, test;

    for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
    {
        candidates[i].votes_fraction = candidates[i].votes/total;

        if (candidates[i].votes_fraction > most_votes)
        {
            most_votes = candidates[i].votes_fraction;
            strcpy(winner, candidates[i].name);
        }
    }
}


int main()
{

    candidate candidates[NUMBER_OF_CANDIDATES];
    int total;
    char winner[20];

    for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
    {
        printf("Enter candidate's name and the number of votes received: ");
        scanf("%s %d", candidates[i].name, &candidates[i].votes);
    }

    total = totalVotes(candidates);
    voteFractions(candidates, total, winner);

    return 0;
}

The problem is that in this statement

candidates[i].votes_fraction = candidates[i].votes/total;

expression

candidates[i].votes/total

uses integer arithmetic because the both operands have type int. As total is always greater than or equal to candidates[i].votes then the result of the division is equal to 0. You have to write

( float )candidates[i].votes/total

Take into account that variable test is declared but not used in function voteFractions . You may remove it.

void voteFractions(candidate *candidates, int total, char *winner)
{
    float most_votes = 0, test;
    //... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM