CS50 C语言作业报错error: expected identifier or '(' { 求助
问题分析与修复
直接触发报错的原因
第11行的int main(void);后面多了分号,函数定义不能以分号结尾,去掉分号即可解决这个语法错误:
// 错误写法 int main(void); { // 正确写法 int main(void) {
其他代码问题及修复
除了上述语法错误,代码还有几处逻辑/语法问题需要修正才能正常运行:
count_letters函数的if语句格式错误
isalpha的调用需要用括号包裹条件,且letters + 1仅为表达式、无赋值操作,无法实现计数累加:// 错误写法 if isalpha(text[i]) { letters + 1 } // 正确写法 if (isalpha(text[i])) { letters++; // 等价于 letters += 1; }未接收count_letters的返回值
main函数中调用count_letters(paragraph)但未将结果赋值给L,导致L始终为0,无法得到正确的字母计数:// 错误写法 count_letters(paragraph); int L = 0; // 正确写法 int L = count_letters(paragraph);Coleman-Liau指数计算精度问题
直接用int存储计算结果会丢失小数部分,应该先以浮点数计算,再通过round函数取整后转成int:// 错误写法 int index = 0.0588 * L - 0.296 * S - 15.8; // 正确写法(需添加math.h头文件) #include <math.h> // ... float index_float = 0.0588 * L - 0.296 * S - 15.8; int index = round(index_float);注:当前代码中S(句子数量)未实现计数逻辑,需补充对应代码才能得到符合要求的可读性指数。
修正后的完整代码
#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <math.h> int count_letters(string text); int main(void) { string paragraph = get_string("Input text: "); int L = count_letters(paragraph); int S = 0; // 需补充句子计数逻辑 float index_float = 0.0588 * L - 0.296 * S - 15.8; int index = round(index_float); printf("%i\n", index); } int count_letters(string text) { int letters = 0; for (int i = 0, length = strlen(text); i < length; i++) if (isalpha(text[i])) { letters++; } return letters; }
内容的提问来源于stack exchange,提问作者BonesOnFire
相关产品推荐
相关产品推荐

