C语言元音统计程序问题:无法统计I/i,求修复方案
问题修复方案
错误分析
- 变量名冲突:用于统计I/i的变量
i和for循环的循环变量重名,导致循环内的操作只会修改循环变量,完全没触碰到统计用的i变量。 - 统计逻辑错误:匹配到I/i时执行的
i++操作,修改的是循环变量而非统计计数变量,完全起不到统计作用。 - 输入格式错误:
scanf("%[^ ]s", &str);存在两处问题:格式串中的换行符需写成\n;数组名str本身就是地址,无需加&。 - 循环边界错误:
i <= len会遍历到字符串末尾的结束符\0,属于无效遍历,正确边界应为i < len。
修复后的代码
#include <stdio.h> #include <string.h> int main () { int len, a = 0, count_i = 0, u = 0, e = 0, o = 0; char str[150]; scanf("%[^\n]", str); len = strlen(str); for(int j = 0; j < len; j++){ if(str[j] == 65 || str[j] == 97){ a++; continue; } if(str[j] == 73 || str[j] == 105){ count_i++; continue; } if(str[j] == 85 || str[j] == 117){ u++; continue; } if(str[j] == 69 || str[j] == 101){ e++; continue; } if(str[j] == 79 || str[j] == 111){ o++; continue; } } printf("A/a : %d\n", a); printf("I/i : %d\n", count_i); printf("E/e : %d\n", e); printf("U/u : %d\n", u); printf("O/o : %d\n", o); return 0; }
修复说明
- 将统计I/i的变量重命名为
count_i,循环变量改为j,彻底解决命名冲突问题。 - 修正
scanf的格式串与参数,正确读取包含空格的输入字符串。 - 调整循环边界为
j < len,仅遍历字符串的有效字符。 - 匹配到I/i时,对
count_i执行自增操作,实现正确计数。
内容的提问来源于stack exchange,提问作者Clarkieeeyyy
相关产品推荐
相关产品推荐

