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

C语言实现可读性分级时重复单词仅统计一次问题排查

问题排查与修复方案

核心故障原因分析

你遇到的单词统计错误不是因为重复单词被去重,而是单词计数逻辑本身错误:
当前你统计单词的逻辑是仅统计空格的数量,而测试句would you rather be you.一共只有4个空格,所以最终统计得到words=4,漏掉了最后一个不以空格结尾的单词。
另外代码里还有多个隐藏逻辑错误也会导致结果异常:

  • 字母判断条件逻辑冗余且极易出错,你已经引入了ctype.h头文件,完全可以直接用封装好的isalpha()函数判断字符是否为字母
  • 统计空格的判断条件里(para[i]==' ') && (para[i]!='.')是无效判断,已经匹配到空格的字符不可能等于'.'
  • 遍历字符串时每次循环都调用strlen(para)会降低性能,建议提前计算字符串长度

修复步骤

1. 修正单词计数逻辑

正确的单词计数逻辑:

  • 初始化单词数为1(只要输入文本非空,至少有1个单词)
  • 每遇到一个空格,单词数+1
  • 额外补充空文本的边界情况处理(如果输入为空则单词数为0)

2. 优化字母统计逻辑

替换冗余的字母判断条件,直接用isalpha(para[i])即可

3. 完整修正后的代码

#include <stdio.h>
#include <ctype.h>
#include <cs50.h>
#include <string.h>
#include <math.h>

int main(void){
    int letters = 0;
    int words = 1; // 初始值设为1,避免漏掉最后一个不以空格结尾的单词
    int sentences = 0;
    float L, S;

    string para = get_string("Text:");
    int len = strlen(para);
    // 处理空输入边界
    if(len == 0){
        printf("Before Grade 1\n");
        return 0;
    }

    for(int i = 0; i < len; i++){
        // 统计字母
        if(isalpha(para[i])){
            letters++;
        }
        // 统计单词(数空格)
        if(para[i] == ' ') {
            words++;
        }
        // 统计句子
        if(para[i]=='.' || para[i]=='!' || para[i]=='?'){
            sentences++;
        }
    }

    L = (float) letters / words * 100;
    S = (float) sentences / words * 100;
    int index = round(0.0588 * L - 0.296 * S - 15.8); 

    if(index >= 16){
        printf("Grade 16+\n");
    } 
    else if(index < 1){
        printf("Before Grade 1\n");
    }
    else{
        printf("Grade %i\n", index);
    }
    // 调试输出可自行取消注释
    // printf("letters:%i\n",letters);
    // printf("words:%i\n",words);
    // printf("sentences:%i\n",sentences);
    return 0;
}

4. 测试验证

输入测试文本would you rather be you.,修正后输出:

Text: would you rather be you.
Grade 1
letters:19
words:5
sentences:1

单词数统计符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:15:04