题目描述
对候选人得票的统计程序。设有3个候选人,每个选民投票输入一个得票的候选人的名字,要求最后输出各人得票结果。
三个候选人的名字分别为Li, Zhang, Fu。
输入
第一行输入输入选票数n
第二行起输入n行,每行是一个候选人名字
输出
三个候选人的统计结果
样例输入
5
Li
Fu
Fu
Zhao
Bai
样例输出
Li:1
Zhang:0
Fu:2
思路
这道题的题意很明确,就是统计字符串的出现次数。
这里说一下字符串比较函数strcmp。头文件是#include <string.h>。
这个函数用于比较两个字符串,返回一个整数值,表示两个字符串的大小关系。比如字符数组str1和str2,也可以用字符串替换,strcmp(str1,str2)函数返回值的意义如下:
如果 str1 等于 str2,则返回 0。
如果 str1 大于 str2,则返回正整数。
如果 str1 小于 str2,则返回负整数。
错误代码
这段代码的思路方向是对的,就是比对字符串。
但是实现有误,首先k定义为int变量,然后又拿去和字符串比较是否相等。
另外,Zhang的Z也写错成了J。
正确的方法应该是用字符数组存名字,再去比较每一位。
#include <stdio.h>
#include <string.h>
int main()
{
int x, y, z, i = 0, j, k, n;
char a[100], b, c[100];
scanf("%d", &n);
for (j = 0; j < 5; j++)
{
gets(a);
for (i = 0; a[i] != '\0'; i++)
{
k = k + a[i];
}
if (k == 'L' + 'i' && a[i - 1] == 'i')
{
x++;
}
else if (k == 'J' + 'h' + 'a' + 'n' + 'g' && a[i - 1] == 'c')
{
y = 0;
}
else if (k == 'F' + 'u' && a[i - 1] == 'u')
{
z++;
}
k = 0;
for (i = 0; a[i] != '\0'; i++)
{
a[i] = '\0';
}
}
printf("Li:%d\nZhang:%d\nFu:%d\n", x, 0, z);
return 0;
}
参考代码
#include <stdio.h>
#include <string.h>
int main()
{
int n;
char name[50];
int countLi = 0, countZhang = 0, countFu = 0;
// 读取选票数
scanf("%d", &n);
// 循环处理每一张选票
for (int i = 0; i < n; i++)
{
// 读取候选人名字
scanf("%s", name);
// 根据候选人名字更新得票数
if (strcmp(name, "Li") == 0)
{
countLi++;
}
else if (strcmp(name, "Zhang") == 0)
{
countZhang++;
}
else if (strcmp(name, "Fu") == 0)
{
countFu++;
}
}
// 输出得票结果
printf("Li:%d\n", countLi);
printf("Zhang:%d\n", countZhang);
printf("Fu:%d\n", countFu);
return 0;
}
(by 归忆)