计算机青铜 2022-03-30 21:53 采纳率: 100%
浏览 22
已结题

计算各类型字符的个数,请问我的代码哪里错了?

有一篇文章,共有3行文字,每行小于80个字符。要求分别统计出其中英文大写字母、小写字母、数字、空格以及其他字符的个数。
请问我的代码哪里错了?感谢解答!

#include <stdio.h>
#include <string.h>
int main(){
    char str[3][80];
  gets(str);
  int up=0,lo=0,di=0,sp=0,ot=0,i,j;
  for(i=0;i<=2;i++)
  {
    for(j=0;j<=80;j++)
    {
      if(str[i][j]>='A'&&str[i][j]<='Z')up++;
      else if(str[i][j]>='a'&&str[i][j]<='z')lo++;
      else if(str[i][j]>='0'&&str[i][j]<='9')di++;
      else if(str[i][j]==' ')sp++;
      else ot++;
    }
  }
  printf("upper case:%d\n",up);
  printf("lower case:%d\n",lo);
  printf("digit:%d\n",di);
  printf("space:%d\n",sp);
  printf("other:%d\n",ot);  
}

img

  • 写回答

1条回答 默认 最新

  • qzjhjxj 2022-03-31 00:38
    关注

    修改处见注释,供参考:

    #include <stdio.h>
    #include <string.h>
    int main()
    {
      int up=0,lo=0,di=0,sp=0,ot=0,i,j; //修改
      char str[3][80]={0};              //修改
    
      for (i = 0;i < 3; i++) //修改
          gets(str[i]);
    
      for(i = 0;i < 3; i++) //for(i = 0;i <= 2; i++)修改
      {
        for(j = 0;str[i][j] != '\0'; j++) //for(j = 0;j <= 80; j++)修改
        {
          if(str[i][j]>='A'&&str[i][j]<='Z')up++;
          else if(str[i][j]>='a'&&str[i][j]<='z')lo++;
          else if(str[i][j]>='0'&&str[i][j]<='9')di++;
          else if(str[i][j]==' ')sp++;
          else ot++;
        }
      }
      printf("upper case:%d\n",up);
      printf("lower case:%d\n",lo);
      printf("digit:%d\n",di);
      printf("space:%d\n",sp);
      printf("other:%d\n",ot);
    
      return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 4月8日
  • 已采纳回答 3月31日
  • 创建了问题 3月30日

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程