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

CS50x(哈佛大学edX课程)Problem Set 2代码输出异常求助

CS50x Readability 程序错误排查

你的程序始终输出"Before Grade 1"的核心问题是Coleman-Liau公式中句子占比(S)的计算完全搞反了。

错误点分析

Coleman-Liau公式要求:

  • L = 每100个单词中的字母数(你的代码这部分是对的)
  • S = 每100个单词中的句子数

但你的代码里写的是:

float S = (float)words / (float)sentences * 100;

这计算的是每100个句子中的单词数,完全和公式要求相反。这个错误会让S的值异常大,代入公式0.0588 * L - 0.296 * S - 15.8后,结果会远小于1,所以无论输入什么都会输出"Before Grade 1"。

另外还有一个潜在问题:如果输入文本没有句子结尾标点(比如只有单个单词),sentences会为0,导致除以0的运行时错误,建议后续可以增加对这种情况的处理。

修复后的代码

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

int main(void)
{
    // 获取用户输入文本
    string text = get_string("Text:  ");

    // 初始化统计变量:单词数初始为1(假设至少有一个单词)
    int letters = 0;
    int words = 1;
    int sentences = 0;

    // 遍历文本统计字母、单词、句子
    for (int i = 0; i < strlen(text); i++)
    {
        // 统计字母
        if (isalpha(text[i]))
        {
            letters++;
        }
        // 统计单词(通过空格判断)
        else if (text[i] == ' ')
        {
            words++;
        }
        // 统计句子(通过结尾标点判断)
        else if (text[i] == '.' || text[i] == '?' || text[i] == '!')
        {
            sentences++;
        }
    }

    // 处理无句子的边界情况(避免除以0)
    if (sentences == 0)
    {
        sentences = 1;
    }

    // 正确计算L和S
    float L = (float)letters / words * 100;
    float S = (float)sentences / words * 100;

    // 计算阅读等级指数
    int index = (int)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);
    }
}

修复说明

  1. 修正了S的计算逻辑,改为(float)sentences / words * 100,符合Coleman-Liau公式要求。
  2. 增加了对sentences == 0的判断,避免除以0的错误。

内容的提问来源于stack exchange,提问作者Not a Guru Jordan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:09:20