在线编译器 C

#include <ctype.h> #include <stdio.h> #include <string.h> int main() { char word[1001]; int count = 0; // scanf("%1000s") while (scanf("%1000s", word) == 1) { int len = strlen(word); // scanf 1 if (len > 0) { // char first_letter = tolower(word[0]); char last_letter = tolower(word[len - 1]); // 1 if (first_letter == last_letter) { count++; } } } // printf("%d\n", count); return 0; }
这段代码的功能是:从标准输入读取多个单词(以空格分隔),统计那些首字母和尾字母相同(忽略大小写)的单词个数,并输出结果。

代码逻辑基本正确,但有一个潜在问题需要注意:

- 当使用 `scanf("%1000s", word)` 读取时,它会将标点符号(如逗号、句号)也当作单词的一部分读入。例如输入 "hello," 时,`word` 的内容是 "hello,",首字母是 'h',尾字母是 ',',这样会导致统计结果与预期不符。

- 可以考虑在判断首尾字母前,先去除单词末尾可能存在的标点符号,或者只检查字母字符。