A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

#include <stdio.h>

int maxIndex(int a[],int length)
{
    int i=0,returnIndex=0;
    for(i;i<length;i++)
    {
        if(a>a[returnIndex]) returnIndex=i;
    }
    return returnIndex;
}

int main()
{
    int count[4]={0,0,0,0};
    int sortC[]={0,1,2,3};
    int temp;
    int i;
    while((temp = getchar()) != '\n')
    {
        if(temp >= 'A' && temp <'E')
        {
            count[temp - 'A']+=1;
        }
    }
    for(i = 0;i<4;i++)
    {
        temp = maxIndex(count,4-i);
        printf("%c:%d次\n",'A' + sortC[temp],count[temp]);

        count[temp]^=count[3-i];
        count[3-i]^=count[temp];
        count[temp]^=count[3-i];

        sortC[temp]^=sortC[3-i];
        sortC[3-i]^=sortC[temp];
        sortC[temp]^=sortC[3-i];
    }

    return 0;
}

4 个回复

倒序浏览
int count[4]={0,0,0,0}; // 对应记录ABCD次数
int sortC[]={0,1,2,3}; // 对应四个字母的顺序
count[temp - 'A']+=1; // temp - 'A'取值为0~3,刚好对应数组元素
temp = maxIndex(count,4-i); // 用这个函数求出count最大元素下标,也就是出现最多的次数
'A' + sortC[temp] // 因为count顺序还是按字母顺序,没有被打乱,所以A~D刚好对应0~3这几个下标,sortC[temp]求出值{0,1,2,3},加上'A'之后对应A~D的ASCII码
count[temp] // 用下表取出元素值,即该字母出现次数
count[temp]^=count[3-i]; // 后面六句是用a = a ^ b; b = a ^ b; a = a ^ b;方式交换取出来的当前这个元素和所在数组最后一个元素,因为字母次数cout和顺序sortC两个数组都做了交换,所以顺序还是对应的。
for(i = 0;i<4;i++) temp = maxIndex(count,4-i); [3-i] // 这几句意味着第一次比较范围0~3,第二次0~2,...保证了比较过得元素不会再次参与比较
回复 使用道具 举报
好久没有看过C语言了啊,感觉好陌生啊
回复 使用道具 举报
从今以后 发表于 2015-1-16 20:36
int count[4]={0,0,0,0}; // 对应记录ABCD次数
int sortC[]={0,1,2,3}; // 对应四个字母的顺序
count[temp  ...

感谢:lol:lol
回复 使用道具 举报

谢谢 了  。标注的很清楚
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马