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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 银河雨 中级黑马   /  2014-11-4 15:30  /  1695 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. #include <stdio.h>

  2. //设定字符串的长度
  3. #define length 100

  4. int main(int argc, const char * argv[])
  5. {
  6.     //设置一个字符串数组
  7.      char string[length];
  8.    
  9.     //输入一个字符串
  10.     for (int i = 0; i <100; i ++) {
  11.         scanf("%c",&string[i]);
  12.         //当输入回车键时,输入结束
  13.         if (string[i] == '\n') {
  14.             break;
  15.         }
  16.     }
  17.     //查看输入的字符串
  18.     printf("输入的字符串是: %s\n",string);
  19.    
  20.     //初始化四个字母的计数器
  21.     int countA = 0, countB = 0, countC = 0, countD = 0;
  22.    
  23.     //计算字母的长度
  24.     for (int i = 0; i < length; i ++) {
  25.         
  26.         if (string[i] == 'A') {
  27.             countA ++;
  28.         }else if (string[i] == 'B')
  29.         {
  30.             countB ++;
  31.         }else if (string[i] == 'C')
  32.         {
  33.             countC ++;
  34.         }else if (string[i] == 'D')
  35.         {
  36.             countD ++;
  37.         }
  38.     }
  39.    
  40.     //打印出字母的数量
  41.     printf("countA = %d\n",countA);
  42.     printf("countB = %d\n",countB);
  43.     printf("countC = %d\n",countC);
  44.     printf("countD = %d\n",countD);
  45.    
  46.     //数字和字母的临时变量
  47.     int tempCount = 0, k;
  48.     char tempLetter;
  49.    
  50.     //将字母的数量和字母分别放入数组
  51.     int countArr[] = {countA,countB,countC,countD};
  52.     char nameArr[] = {'A','B','C','D'};
  53.    
  54.     //将数量进行升序排序
  55.     for (int i = 0; i < 4; i ++) {
  56.         for (int j = i + 1; j < 4; j ++) {
  57.             
  58.             //每次遍历都重置k的初始值
  59.             k = i;
  60.             
  61.             //后面的数比前面的大,就把k换成大的数的下标
  62.             if (countArr[j] > countArr[k]) {
  63.                 k = j;
  64.             }
  65.             //如果后面的数字比前面的大,就交换数字和字母
  66.             if (k != i) {
  67.                 tempCount = countArr[i];
  68.                 countArr[i] = countArr[j];
  69.                 countArr[j] = tempCount;
  70.                
  71.                 tempLetter = nameArr[i];
  72.                 nameArr[i] = nameArr[j];
  73.                 nameArr[j] = tempLetter;
  74.             }
  75.         }
  76.     }
  77.    
  78.     //打印排序后的结果
  79.     for (int i = 0; i < 4; i ++) {
  80.         printf("%c = %d\n",nameArr[i],countArr[i]);
  81.     }
  82.    
  83.    
  84.     return 0;
  85. }
复制代码


1 个回复

倒序浏览
多谢分享
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马