统计候选人票数,设有3个候选人每次输入一个得票的候选人的名字,要求最后输出三个候选人的得票结果
时间: 2024-03-25 11:41:11 浏览: 33
可以使用数组来存储三个候选人的得票数,每次输入一个候选人的名字后,将其对应的数组元素加1,最后输出三个候选人的得票结果。
以下是C语言代码实现:
```c
#include <stdio.h>
#include <string.h>
int main() {
// 定义候选人数组和得票数数组
char candidates[3][20] = {"Alice", "Bob", "Charlie"};
int votes[3] = {0, 0, 0};
// 输入候选人名字并统计得票数
for (int i = 0; i < 10; i++) { // 假设有10个人投票
char name[20];
printf("Please enter the name of the candidate you vote for: ");
scanf("%s", name);
if (strcmp(name, candidates[0]) == 0) {
votes[0]++;
} else if (strcmp(name, candidates[1]) == 0) {
votes[1]++;
} else if (strcmp(name, candidates[2]) == 0) {
votes[2]++;
} else {
printf("Invalid candidate name.\n");
}
}
// 输出得票结果
printf("The voting result:\n");
for (int i = 0; i < 3; i++) {
printf("%s: %d votes\n", candidates[i], votes[i]);
}
return 0;
}
```
假设有10个人投票,输出结果可能为:
```
Please enter the name of the candidate you vote for: Alice
Please enter the name of the candidate you vote for: Bob
Please enter the name of the candidate you vote for: Alice
Please enter the name of the candidate you vote for: Charlie
Please enter the name of the candidate you vote for: Bob
Please enter the name of the candidate you vote for: Alice
Please enter the name of the candidate you vote for: Bob
Please enter the name of the candidate you vote for: Alice
Please enter the name of the candidate you vote for: Charlie
Please enter the name of the candidate you vote for: Alice
The voting result:
Alice: 4 votes
Bob: 3 votes
Charlie: 3 votes
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)