CS50X Readability程序单个测试用例输出异常求助
问题情况
- 测试文本保留末尾点号时,预期输出
Grade 8,实际输出Grade 7;去掉末尾点号后结果符合预期 - 测试文本:
When he was nearly thirteen, my brother Jem got his arm badly broken at the elbow. When it healed, and Jem's fears of never being able to play football were assuaged, he was seldom self-conscious about his injury. His left arm was somewhat shorter than his right; when he stood or walked, the back of his hand was at right angles to his body, his thumb parallel to his thigh.
问题根源
你的count_words函数仅将字母和单引号'视为单词的有效字符,但英文中带连字符-的复合词(比如self-conscious)属于单个单词。当前代码遇到-时会将其视为单词分隔符,把self-conscious拆成两个单词,导致单词数w被多统计。
单词数被多算后,Coleman-Liau指数公式中的lResult(每100单词的字母数)和sResult(每100单词的句子数)都会变小:
lResult的系数为正,它的减小会拉低指数值sResult的系数为负,它的减小会抬高指数值
两者综合作用下,指数整体被拉低,再加上末尾点号增加了一个句子数,最终让round(index)的结果从8变成7。
解决方案
修改count_words函数的判断条件,将连字符-加入到单词有效字符中:
int count_words(string text) { int wordsCount = 0; int ifWord = 0; for(int i = 0; text[i] != '\0'; i++) { // 新增对连字符的判断,复合词视为单个单词 if (isalpha(text[i]) || text[i] == '\'' || text[i] == '-') { if (!ifWord) { ifWord = 1; wordsCount++; } } else { ifWord = 0; } } return wordsCount; }
验证说明
修改后,self-conscious会被正确统计为一个单词,单词数w的统计值准确。此时再计算带末尾点号的测试文本,index的值会被正确计算为接近8的数值,round(index)后输出Grade 8。
内容的提问来源于stack exchange,提问作者CiMoran

