编程统计候选人的得票数。设有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: " "%8s:%d " "Wrong election:%d " 注意: A. 上述输出格式中,"%8s:%d "中%8s表示输出候选人的姓名;%d表示输出相应候选人的的票数。 B. 另外,无论是否存在废票的情况,最终都需要输出"Wrong election:%d "。 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: "); for (i = 0; i < 3; i++) { printf("%8s:%d ", vote[i].name, vote[i].count); } printf("Wrong election:%d ", 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: "); for (i = 0; i < 3; i++) { printf("%8s:%d ", arr[i].name, arr[i].count); } printf("Wrong election:%d ", wrong); }
strcasecmp()用来比较参数s1 和s2 字符串,比较时会自动忽略大小写的差异。