选票统计,定义结构体和编写子函数

编程统计候选人的得票数。设有3个候选人zhang, li, wang(候选人姓名不区分大小写),10个选民,选民每次输入一个得票的候选人的名字,若选民输错候选人姓名,则按废票处理。选民投票结束后程序自动按得票数从高到低显示各候选人的得票结果和废票信息。要求用结构体数组candidate表示3个候选人的姓名和得票结果。


#include <stdio.h>
#include <string.h>
/***定义struct candidate及其数组***/

/*************************/
int Election(struct candidate *candidate);
void sort(struct candidate *candidate);
int main(void)
{
    int i,wrong;
    wrong=Election(candidate);
    sort(candidate);
    for(i=0; i<3; i++)
        printf("%s %d\n",candidate[i].name, candidate[i].count);
    printf("wrong election %d\n", wrong);
    return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct {
    char name[20];
    int votes;
} Candidate;

int compare(const void* a, const void* b) {
    Candidate* c1 = (Candidate*)a;
    Candidate* c2 = (Candidate*)b;
    return c2->votes - c1->votes;
}

int main() {
    Candidate candidates[3] = {
        {"zhang", 0},
        {"li", 0},
        {"wang", 0}
    };

    int invalidVotes = 0;
    for (int i = 0; i < 10; i++) {
        printf("请输入您要投票的候选人的姓名:");
        char name[20];
        scanf("%s", name);

        int found = 0;
        for (int j = 0; j < 3; j++) {
            if (strcmp(name, candidates[j].name) == 0) {
                candidates[j].votes++;
                found = 1;
                break;
            }
        }

        if (!found) {
            invalidVotes++;
        }
    }

    qsort(candidates, 3, sizeof(Candidate), compare);

    for (int i = 0; i < 3; i++) {
        printf("%s: %d 票\n", candidates[i].name, candidates[i].votes);
    }

    printf("废票:%d 张\n", invalidVotes);

    return 0;
}