C语言编译报unknown type name 'count'等错误的原因是什么
编译报错原因及代码修复方案
一、编译错误的核心触发原因
- 头文件缺失:代码中使用了
printf/scanf(需引入<stdio.h>)、strlen/strcmp(需引入<string.h>),未声明的函数会被编译器误判类型,触发常量相关报错。 - 变量声明位置不符合C89标准要求:老旧C标准要求所有变量必须定义在代码块的最顶部,你在输入逻辑之后才定义
q/w/t/count变量,编译器会识别为未知类型,触发unknown type name 'count'报错。如果你的编译器默认用C89模式,要么把变量声明移到main函数开头,要么加编译参数指定用C99及以上标准。 - 大括号不匹配:你的代码末尾多写了2个多余的闭合
},导致语法结构错乱,触发expected identifier or '(' before '}' token报错。
二、代码逻辑存在的其他问题
- 条件判断写错:
if (q = 0)是赋值操作,永远为假,应该改为相等判断if (q == 0)。 - 入参格式错误:
scanf("%s", &string[i])中string[i]本身就是字符数组的首地址,不需要加取地址符&。 - 去重计数逻辑错误:当前遍历前面字符串的逻辑中,只要和某一个前面的字符串不重复就加1,会导致同一个字符串被多次计数,正确逻辑应该是遍历完所有前面的字符串确认无重复后,再给count加1。
- 长度判断要求不符:需求是统计长度超过10的字符串,应该用
t > 10而非t >= 10。
三、修正后的完整代码
#include <stdio.h> #include <string.h> int main() { // 所有变量声明在代码块开头,兼容C89标准 char string[1000][1000]; int i, o = 1, sentence; int q, w, t, count = 0; int is_dup; printf("enter the number of speeches: "); scanf("%d", &sentence); for (i = 0; i < sentence; i++) { printf("\nplease enter speech number %d: ", o); scanf("%s", string[i]); o++; } for(q = 0; q < sentence; q++) { t = strlen(string[q]); // 筛选长度超过10的字符串 if (t > 10) { is_dup = 0; // 和前面所有字符串比对去重 for(w = 0; w < q; w++) { if (strcmp(string[q], string[w]) == 0) { is_dup = 1; break; } } // 无重复才计数 if (!is_dup) { count++; } } } printf("%d", count); return 0; }
内容的提问来源于stack exchange,提问作者jonathan kevin
相关产品推荐
相关产品推荐

