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

如何修改C语言代码以运行时打印全部26个英文字母?

问题分析与修复方案

问题根源

原代码的for循环条件str[i] != 0是在遍历输入字符串的字符,而非遍历存储26个英文字母频率的count数组。这就导致循环只会执行到输入字符串的末尾,根本无法覆盖全部26个字母的统计结果。

修复步骤

  • 把输出频率的for循环条件改成遍历0到25(对应a-z的26个字母),替换原循环条件即可。
  • 顺带修正一个潜在bug:scanf("%s", &str);里的&是多余的,数组名str本身就是指向数组首元素的指针,直接写scanf("%s", str);即可,避免编译警告或未定义行为。

修改后的完整代码

#include <stdio.h>

int main(){
    int i = 0;
    int count[26] = {0};
    char str[100];

    printf("Ord: ");
    scanf("%s", str);
    printf("Frekvens:\n");

    while (str[i] != '\0'){
        if (str[i] >= 'a' && str[i] <= 'z'){
            int x = str[i] - 'a';
            count[x]++;
        }
        i++;
    }

    // 修改后的for循环,遍历全部26个字母对应的计数
    for (i = 0; i < 26; i++){
        printf("'%c' : %d\n", i + 'a', count[i]);
    }

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:10:38