根据提示,在右侧编辑器Begin-End处补充代码,输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数。
```c++
#include<stdio.h>
int main(void)
{
/*********Begin*********/
char b;
int letters=0, space=0, digit=0, other=0;
while(b!='\n'){
if((b>='A'&&b<='Z')||(b>='a'&&b<='z'))
{
letters++;
}
else if (b>='0'&&b<='9')
{
digit++;
}
else if (b==' ')
{
space++;
}
else
{
other++;
}
scanf("%c",&b);
}
printf("%d %d %d %d", letters, digit, space, other);
return 0;
}
/*********End**********/
``
为什么最后的OTHER要减一
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
关注在这段代码中,最后的OTHER要减一的原因是因为在统计其他字符的个数时,没有排除换行符'\n'。当输入的字符为换行符时,程序会将其计入其他字符的个数,导致结果不准确。为了解决这个问题,我们需要在统计其他字符的个数之前,先判断当前字符是否为换行符,如果是则跳过,不计入其他字符的个数。
修改后的代码如下:
#include<stdio.h> int main(void) { /*********Begin*********/ char b; int letters=0, space=0, digit=0, other=0; while(b!='\n'){ if((b>='A'&&b<='Z')||(b>='a'&&b<='z')) { letters++; } else if (b>='0'&&b<='9') { digit++; } else if (b==' ') { space++; } else if (b != '\n') // 添加判断条件,排除换行符 { other++; } scanf("%c",&b); } printf("%d %d %d %d", letters, digit, space, other-1); // 将other减一后再输出 return 0; /*********End**********/ }解决 无用评论 打赏 举报