whdksdhdhwkd 2023-11-14 20:17 采纳率: 0%
浏览 1

为什么最后的OTHER要减一

根据提示,在右侧编辑器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**********/ 
       
``
  • 写回答

2条回答 默认 最新

  • 玥轩_521 优质创作者: 信息安全技术领域 2023-11-14 20:38
    关注

    在这段代码中,最后的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**********/ 
    }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 11月14日