用c语言,设有三个候选人,每次输入一个得票的候选人名字,要求最后输出各内得票数。
时间: 2024-02-20 16:01:08 浏览: 20
好的,以下是使用 C 语言编写的程序来实现这个任务:
```c
#include <stdio.h>
#include <string.h>
int main() {
// 初始化候选人得票数为0
int candidate1_votes = 0;
int candidate2_votes = 0;
int candidate3_votes = 0;
while (1) {
// 提示用户输入候选人名字
char candidate_name[20];
printf("请输入候选人名字:");
scanf("%s", candidate_name);
// 根据输入的名字更新对应候选人的得票数
if (strcmp(candidate_name, "候选人1") == 0) {
candidate1_votes++;
} else if (strcmp(candidate_name, "候选人2") == 0) {
candidate2_votes++;
} else if (strcmp(candidate_name, "候选人3") == 0) {
candidate3_votes++;
} else {
printf("输入错误,请输入候选人名字\n");
}
// 判断是否结束投票
char is_end[2];
printf("是否结束投票?(y/n)");
scanf("%s", is_end);
if (strcmp(is_end, "y") == 0) {
break;
}
}
// 输出各个候选人的得票数
printf("候选人1得票数:%d\n", candidate1_votes);
printf("候选人2得票数:%d\n", candidate2_votes);
printf("候选人3得票数:%d\n", candidate3_votes);
return 0;
}
```
这段代码使用 `while` 循环不断提示用户输入候选人名字,根据输入的名字更新对应候选人的得票数,直到用户输入"y"结束投票。最后,程序会输出各个候选人的得票数。