运行结果:
代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//定义颜色结构体
typedef struct _color
{
char color[22]; //颜色
int nmb; //颜色出现次数
}Color;
int main()
{
int n, i, j;
Color cc[5000]; //存储所有的颜色及出现次数
char tmp[22]; //临时存储读取的颜色
int cnt = 0; //每组测试数据中不同颜色的个数
int index = 0; //出现次数最多的颜色再数据中的下标
while (scanf("%d", &n) != EOF) //读取n,遇到文件结束符结束
{
cnt = 0; //每次都要重置这个不同颜色的个数
for (i = 0; i < n; i++) //读取n个颜色
{
scanf("%s", tmp);
//判断颜色是否已经存在
for (j = 0; j < cnt; j++)
{
if (strcmp(cc[j].color, tmp) == 0) //比较颜色,如果已经存在,就把这个颜色的数量+1
{
cc[j].nmb += 1;
break;
}
}
if (j == cnt)//如果新读取的颜色不存在,就把这个颜色添加到数组中,并把该颜色的数量设置为1
{
cc[cnt].nmb = 1;
strcpy(cc[cnt].color, tmp); //颜色拷贝到数组元素中
cnt++;//不同颜色的个数+1
}
}
//查找出现次数最多的
index = 0;//记录出现次数最多的颜色下标
for (i = 1; i < cnt; i++) //遍历颜色结构体数组,找到出现次数最多的颜色,并记录下标
{
if (cc[i].nmb > cc[index].nmb) //如果i出现的次数比index多,就更新index
index = i;
else if (cc[i].nmb == cc[index].nmb)//如果两者出现的次数相等,就判断颜色的ASCII值
{
if (strcmp(cc[i].color, cc[index].color) < 0) //如果i的ASCII小,就更新index
index = i; //更新index的值
}
}
//输出
printf("%s\n", cc[index].color);
}
return 0;
}