CS50 Pset2 Readability程序问题:check50测试输出不符合预期
问题:阅读等级计算程序check50测试失败
我写了一个计算文本阅读等级的程序,但运行check50时总是出错。比如在处理单句内标点的测试点中,预期输出是Grade 9\n,但实际输出包含多余内容导致不匹配。目前程序仅能正确处理1年级以下的阅读等级。
我的代码如下:
#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <math.h> int main(void) { //prompt user for text string text = get_string("Text: "); { printf("%s\n", text); } int count_letters(string letters); // count letters int letters = 0; int n = 0; while (text[n]) { if (isalpha(text[n]) != '\0') { letters++; } n++; } //print number of letters printf("%i letters\n", letters); //count words int count_words(string words); int words = 0; int x = 0; while (text[x]) { if ((text[x]) == ' ') { words++; } x++; } //print number of words printf("%i words\n", words); // count sentences int count_sentences(string sentences); int sentences = 0; int s = 0; while (text[s]) { if (ispunct(text[s])) { sentences++; } s++; } //print number of sentences printf("%i sentences\n", sentences); //formula = index = 0.0588 * L(letters per 100 words) - 0.296 * S(sentences per 100 words) - 15.8 float L = ((float)letters / words) * 100; float S = ((float)sentences / words) * 100; int grade = round(0.0588 * L) - (0.296 * S) - 15.8; if (grade < 1) { printf("Before Grade 1\n"); } else if (grade > 16) { printf("Grade 16+\n"); } else { printf("Grade %i\n", grade); } }
问题原因及修复方案
1. 多余调试输出干扰check50判断
代码中打印输入文本、字母数、单词数、句子数的语句会导致输出内容与check50预期不符,直接删除这些printf语句即可。
2. 单词计数逻辑错误
当前通过统计空格数计算单词数,但正确的单词数应为空格数+1(比如"Hello world"有1个空格,对应2个单词)。修改代码:
int words = 1; // 初始化为1,因为至少有一个单词 int x = 0; while (text[x]) { if (text[x] == ' ') { words++; } x++; }
3. 句子计数逻辑错误
当前用ispunct判断所有标点,但只有**句号(.)、感叹号(!)、问号(?)**才算句子结束。修改判断条件:
int sentences = 0; int s = 0; while (text[s]) { if (text[s] == '.' || text[s] == '!' || text[s] == '?') { sentences++; } s++; }
4. 阅读等级公式计算错误
原代码仅对0.0588 * L取整,正确做法是对整个公式结果取整:
float index = 0.0588 * L - 0.296 * S - 15.8; int grade = round(index);
修复后的完整代码
#include <cs50.h> #include <stdio.h> #include <ctype.h> #include <math.h> int main(void) { // 读取用户输入的文本 string text = get_string("Text: "); // 统计字母数 int letters = 0; int n = 0; while (text[n]) { if (isalpha(text[n])) { letters++; } n++; } // 统计单词数 int words = 1; int x = 0; while (text[x]) { if (text[x] == ' ') { words++; } x++; } // 统计句子数 int sentences = 0; int s = 0; while (text[s]) { if (text[s] == '.' || text[s] == '!' || text[s] == '?') { sentences++; } s++; } // 计算L和S值 float L = ((float)letters / words) * 100; float S = ((float)sentences / words) * 100; // 计算阅读等级 float index = 0.0588 * L - 0.296 * S - 15.8; int grade = round(index); // 输出结果 if (grade < 1) { printf("Before Grade 1\n"); } else if (grade > 16) { printf("Grade 16+\n"); } else { printf("Grade %i\n", grade); } }
内容的提问来源于stack exchange,提问作者rubix
相关产品推荐
相关产品推荐

