编辑代码

#include <stdio.h>
#include <string.h>

#define MAX_VOTERS 100

typedef struct {
    char id[20];
} Voter;

typedef struct {
    Voter voters[MAX_VOTERS];
    int count;
} VoterRegistry;

void initVoterRegistry(VoterRegistry* registry) {
    registry->count = 0;
}

int hashFunction(const char* id) {
    int hash = 0;
    for (int i = 0; id[i] != '\0'; ++i) {
        hash += id[i];
    }
    return hash % MAX_VOTERS;
}

int isVoterRegistered(const VoterRegistry* registry, const char* voterId) {
    int hash = hashFunction(voterId);

    for (int i = 0; i < registry->count; ++i) {
        if (strcmp(registry->voters[i].id, voterId) == 0) {
            return 1;  // 已注册
        }
    }

    return 0;  // 未注册
}

void vote(VoterRegistry* registry, const char* voterId) {
    if (isVoterRegistered(registry, voterId)) {
        printf("Voter %s has already voted.\n", voterId);
    } else {
        if (registry->count < MAX_VOTERS) {
            strcpy(registry->voters[registry->count].id, voterId);
            registry->count++;
            printf("Voter %s is casting their vote.\n", voterId);
        } else {
            printf("Voter registry is full. Cannot register more voters.\n");
        }
    }
}

int main() {
    VoterRegistry voterRegistry;
    initVoterRegistry(&voterRegistry);

    // 投票
    vote(&voterRegistry, "John");
    vote(&voterRegistry, "Jane");
    vote(&voterRegistry, "John");  // 重复投票,会输出提示

    // 检查是否注册
    printf("John is registered: %s\n", isVoterRegistered(&voterRegistry, "John") ? "true" : "false"); // 输出 true
    printf("Bob is registered: %s\n", isVoterRegistered(&voterRegistry, "Bob") ? "true" : "false");   // 输出 false

    return 0;
}