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

CS50x Readability作业求助:预期输出Grade5却得到Grade4

CS50x 2024 Readability作业问题排查

问题概述

做CS50x 2024的Readability作业时,输入以下文本:

Harry Potter was a highly unusual boy in many ways. For one thing, he hated the summer holidays more than any other time of year. For another, he really wanted to do his homework, but was forced to do it in secret, in the dead of the night. And he also happened to be a wizard.

预期输出应为Grade 5,但代码始终输出Grade 4。误以为是取整逻辑的问题,但修改取整方式会破坏其他测试用例的结果。

问题根源

不是取整逻辑的问题,而是字母统计遗漏了字母Z:

  • 代码中定义了包含26个大写字母的数组letters,但循环判断时用了j < 25,只检查到字母Y,Z不会被识别为字母,导致统计的字母数少1。
  • 输入文本中的wizard包含字母Z,因此实际统计的字母数比正确值少1,直接导致Coleman-Liau指数计算值偏低,最终round()后得到4而非5。

验证计算

正确数值:

  • 字母数:215,单词数:56,句子数:4
  • L = (215*100)/56 ≈ 383.93
  • S = (4*100)/56 ≈7.14
  • 指数:0.0588383.93 -0.2967.14 -15.8 ≈4.66 → round后为5

你的代码统计的字母数是214,计算出的指数≈4.56 → round后为4。

修复方案

方案1:修正循环条件

将字母检查循环的条件从j < 25改为j < 26,确保所有26个字母都被统计:

for (int j = 0; j < 26; j++)

方案2:简化字母判断(更推荐)

直接使用ctype.h中的isalpha()函数替代循环对比数组,避免手动枚举字母的错误:

// 替换原有的字母、空格、句子结束符判断逻辑
currentcharacter = text[i];
if (isalpha(currentcharacter)) {
    number_of_letters++;
} else if (isspace(currentcharacter)) {
    number_of_spaces++;
} else if (currentcharacter == '.' || currentcharacter == '!' || currentcharacter == '?') {
    number_of_periods++;
}

这样无需处理大小写转换(isalpha()对大小写字母都返回真),也不会遗漏任何字母。

修改后的完整代码

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

int main(void)
{
    string text = get_string("Text: ");

    int number_of_spaces = 0;
    int number_of_letters = 0;
    int number_of_sentences = 0;

    // 遍历文本字符
    for (int i = 0; text[i] != '\0'; i++)
    {
        if (isalpha(text[i])) {
            number_of_letters++;
        } else if (isspace(text[i])) {
            number_of_spaces++;
        } else if (text[i] == '.' || text[i] == '!' || text[i] == '?') {
            number_of_sentences++;
        }
    }

    int number_of_words = number_of_spaces + 1;

    double L = ((double) number_of_letters * 100) / number_of_words;
    double S = ((double) number_of_sentences * 100) / number_of_words;

    double gradelevel = 0.0588 * L - 0.296 * S - 15.8;

    if (gradelevel < 1)
    {
        printf("Before Grade 1\n");
    }
    else if (gradelevel >= 16)
    {
        printf("Grade 16+\n");
    }
    else
    {  
        printf("Grade %.f\n", round(gradelevel));
    }

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 21:29:51