You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

统计单词重复字母组数的C语言程序异常排查求助

问题分析与解决

你的代码核心问题是最后输出的是最后一个字符的出现次数,完全没实现题目要求的统计重复字母组的逻辑。比如输入taylor时,最后一个字符是r,它的出现次数是1,所以输出1,但实际需要统计的是有多少种字母出现了重复(即出现次数≥2),无重复的话就输出0。

正确实现思路

题目要求的逻辑本质是统计有多少个不同的字母出现了至少两次。你已经用count数组统计了每个字母的出现次数,接下来只需要遍历这个数组,数里面值≥2的元素个数即可。

修改后的代码(计数数组版)

#include <stdio.h>

int main(void) {
    char string[51];
    int c = 0, count[26] = { 0 }, result = 0;
   
    scanf("%s", string); 
    while (string[c] != '\0') {
        if (string[c] >= 'a' && string[c] <= 'z') {
            int x = string[c] - 'a';
            count[x]++;
        }
        c++;
    }

    // 遍历计数数组,统计出现次数≥2的字母数量
    for (int i = 0; i < 26; i++) {
        if (count[i] >= 2) {
            result++;
        }
    }

    printf("%d", result);

    return 0;
}

修改说明

  1. 将原全局变量x移到循环内部(无需全局保留),新增result变量存储最终统计结果。
  2. 新增for循环遍历count数组,每遇到计数≥2的字母,就给result加1。
  3. 最后输出result而非count[x]。

严格按题目步骤实现(排序遍历版)

如果要完全遵循题目描述的“先按ASCII排序,再遍历比较相邻字符并跳过重复”的步骤,可使用以下代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
    char string[51];
    scanf("%s", string);
    int len = strlen(string);
    // 对字符串按ASCII码顺序排序
    qsort(string, len, sizeof(char), (int (*)(const void*, const void*))strcmp);
    
    int result = 0;
    int i = 0;
    while (i < len - 1) {
        if (string[i] == string[i+1]) {
            result++;
            // 跳过后续所有相同字符,避免重复计数
            while (i < len - 1 && string[i] == string[i+1]) {
                i++;
            }
        }
        i++;
    }
    
    printf("%d", result);
    return 0;
}

测试验证

  • 输入apple:输出1(符合预期)
  • 输入erroneousnesses:输出5(符合预期)
  • 输入taylor或yup:输出0(符合预期)

内容的提问来源于stack exchange,提问作者C_luna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:20:41