C语言。统计字符串字数并计算各类字符占总字符数的比例。
如图,显然不对,请问是什么地方出了问题?
#include
#include
int main()
{
char ch[80];
int lc,sc,dc,n;
lc=sc=dc=0;
gets(ch);
n = strlen(ch);
for(int i = 0;ch[i]!='\n';i++)
{
if(ch[i]>='A'&&ch[i]<='Z')
lc++;
if(ch[i]>='a'&&ch[i]<='z')
sc++;
if(ch[i]>='0'&&ch[i]<='9')
dc++;
}
printf("共%d个字符\n其中%d个大写字母\n %d个小写字母\n %d个数字\n",n,lc,sc,dc);
printf("其中,大写字母占%.2f,小写字母占%.2f,数字占%.2f。",(float)lc/n,(float)sc/n,(float)dc/n);
return 0;
}
第10行的for循环结束条件不对,可以改为ch[i]!='\0'或者i<n,即只判断到输入的字符串最后一个字符,如果是ch[i]!='\n',则会数组越界,因为输入的换行使用gets获取字符串不会存储在数组中,所以会访问到超过数组最大下标,直到遇到一个换行符才停止循环。
修改如下:
参考链接:
#include<stdio.h>
#include<string.h>
int main()
{
char ch[80];
int lc,sc,dc,n;
lc=sc=dc=0;
// https://baike.baidu.com/item/gets/787649?fr=aladdin
gets(ch); // oaidncpaoIHIOUGLKf093284900fjs
n = strlen(ch);
// for循环的结束条件改为ch[i]!='\0'或者i<n,即只判断到输入的字符串最后一个字符
int i;
for(i = 0;ch[i]!='\n';i++)
{
// http://ascii.wjccx.com/
// printf("ch[%d]=%d,ch[%d]=%c\n",i,ch[i],i,ch[i]);
if(ch[i]>='A'&&ch[i]<='Z')
lc++;
if(ch[i]>='a'&&ch[i]<='z')
sc++;
if(ch[i]>='0'&&ch[i]<='9')
dc++;
}
// printf("ch[%d]=%d,ch[%d]=%c\n",i,ch[i],i,ch[i]);
printf("共%d个字符\n其中%d个大写字母\n %d个小写字母\n %d个数字\n",n,lc,sc,dc);
printf("其中,大写字母占%.2f,小写字母占%.2f,数字占%.2f。",(float)lc/n,(float)sc/n,(float)dc/n);
return 0;
}
gets会造成越界,不安全,用fgets函数。
gets(ch); 改为用: gets_s(ch, 80);
for(int i = 0;ch[i]!='\n';i++) 修改为: for(int i = 0;ch[i]!='\0';i++)