【C语言】统计候选人的得票数

编程统计候选人的得票数。设有3个候选人zhang、li、wang(候选人姓名不区分大小写),
10个选民,选民每次输入一个得票的候选人的名字,若选民输错候选人姓名,则按废票处理。
选民投票结束后程序自动显示各候选人的得票结果和废票信息。要求用结构体数组candidate
表示3个候选人的姓名和得票结果。 例如: Input vote 1:li Input vote 2:li Input vote 3:Zhang Input vote 4:wang Input vote 5:zhang Input vote 6:Wang Input vote 7:Zhang Input vote 8:wan Input vote 9:li Input vote 10:lii Election results: li:3 zhang:3 wang:2 Wrong election:2 输入格式: "Input vote %d:" "%s" 输出格式: "Election results:\n" "%8s:%d\n" "Wrong election:%d\n" 注意: A. 上述输出格式中,"%8s:%d\n"中%8s表示输出候选人的姓名;%d表示输出相应候选人的的票数。 B. 另外,无论是否存在废票的情况,最终都需要输出"Wrong election:%d\n"。 C. 本题要求使用结构体。
 
#include<stdio.h>
#include<string.h>
typedef struct vote
{
    char name[10];
    int count;
} VOTE;
main()
{
    VOTE vote[10]={{"li",0},{"zhang",0},{"wang",0},{"Zhang",0},{"Wang",0}};
    int i;
    char name[10];
    for (i = 0; i < 10; i++)
    {
        printf("Input vote %d:", i + 1);
        scanf("%s", name);
        if (strcmp(vote[2].name, name) == 0 || strcmp(vote[4].name, name) == 0)
            vote[2].count++;
        else if (strcmp(vote[0].name, name) == 0)
            vote[0].count++;
        else if (strcmp(vote[3].name, name) == 0 || strcmp(vote[1].name, name) == 0)
            vote[1].count++;
        else
            vote[3].count++;
    }
    printf("Election results:\n");
    for (i = 0; i < 3; i++)
    {
        printf("%8s:%d\n", vote[i].name, vote[i].count);
    }
    printf("Wrong election:%d\n", vote[3].count);
}
方法一
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
struct Candidate
{
    char name[10];
    int count;
};
int main()
{
    struct Candidate arr[3] = {
        "li",0,"zhang",0,"wang",0
    };
    int i = 0, j = 0;
    char s[10];
    int wrong = 0;
    int flag = 0;
    for (i = 0; i < 10; i++)
    {
        flag = 0;
        printf("Input vote %d:", i + 1);
        scanf("%s", s);
        for (j = 0; j < 3; j++)
        {
            if (strcasecmp(arr[j].name, s) == 0)
                {
                    arr[j].count++;
                    flag = 1;
                }
        }
        if (flag == 0)
        {
            wrong++;
        }
    }

    printf("Election results:\n");
    for (i = 0; i < 3; i++)
    {
        printf("%8s:%d\n", arr[i].name, arr[i].count);
    }

        printf("Wrong election:%d\n", wrong);
}
方法二

strcasecmp()用来比较参数s1 和s2 字符串,比较时会自动忽略大小写的差异。

posted @ 2021-06-16 21:52  油菜园12号  阅读(1262)  评论(0编辑  收藏  举报