CS50 Pset2 Readability代码重复输出年级水平问题求助
CS50 Pset2 Readability:结果重复打印问题
测试文本 "Red fish, blue fish, one fish, two fish." 时,虽然能输出正确结果 Before Grade 1,但该结果会重复打印多次,问题出在循环逻辑上。
你的原代码:
int main(void) { //Text from User string text = get_string("Text: "); 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++; } float L = (float) letters / (float) words * 100; float S = (float) sentences / (float) words * 100; int index = round(0.0588 * L - 0.296 * S - 15.8); if (index < 1) { printf("Before Grade 1\n"); } else if (index > 16) { printf("Grade 16+\n"); } else { printf("Grade %i\n", index); } } }
问题原因
你把可读性指数的计算和打印代码放在了for循环内部,循环每遍历文本中的一个字符,就会执行一次计算和打印操作。文本有多少个字符,就会输出多少次结果,所以才会重复打印。
修正后的代码
只需要把计算和打印的逻辑移到for循环外面,等统计完所有字母、单词、句子数量后,再执行一次计算和打印即可:
#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <math.h> int main(void) { // 获取用户输入的文本 string text = get_string("Text: "); 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++; } } // 计算可读性指数 float L = (float) letters / words * 100; float S = (float) sentences / words * 100; int index = round(0.0588 * L - 0.296 * S - 15.8); // 根据指数输出结果 if (index < 1) { printf("Before Grade 1\n"); } else if (index > 16) { printf("Grade 16+\n"); } else { printf("Grade %i\n", index); } return 0; }
内容的提问来源于stack exchange,提问作者JaceH
相关产品推荐
相关产品推荐

