#include
int main()
{
int letter=0,digit=0,blank=0,other=0;
char ch;
do
{
scanf("%c",&ch);
if ((ch>='a')&&(ch<='z')||(ch>='A')&&(ch<='Z'))
{
letter++;
continue;
}
if (ch>='0'&& ch<='9') //不符合语法
{
digit++;
continue;
}
if (ch==' ') //少了等号
{
blank++;
continue;
}
other++;
}
while ( ch!='\n');
printf("%d %d %d %d", letter,digit,blank,other);
return 0;
}
附上结果吧。满意请采纳,若有疑问请追问
#include
#include
void main()
{
char a[20];
int j=0,c=0,b=0,d=0;
printf("请输入20个字符的字符串:");
gets(a);
for(int i=0;i<20;i++)
{
if(a[i]>='0'&&a[i]<='9')
j++;
else if(a[i]>='a'&&a[i]<='z'||a[i]>='A'&&a[i]<='Z')
c++;
else if(a[i]==' ')
b++;
else
d++;
}
printf("数字:%d\n",j);
printf("字母:%d\n",c);
printf("空格:%d\n",b);
printf("其他字符:%d\n",d);
}
分别统计大小字母、空格、数字和其他字符的个数。
#include
int main()
{
int letter=0,digit=0,blank=0,other=0;
char ch;
do
{scanf("%c",&ch);
if ((ch>='a')&&(ch<='z')||(ch>='A')&&(ch<='Z'))
letter++;
if ('0'<= ch<='9') //'0'<=ch && ch<='9'
digit++;
else
if (ch=' ') //ch==' '
blank++;
else
other++;
}
while ( ch!='\n');
printf("%d %d %d %d", letter,digit,blank,other);
return 0;
}
哪里有问题,谢谢
digit的计算结果会出问题 0<= ch <=9;空格会计算在digit中。
if else不能计算blank 和other,要ch == ' ' .
循环会多走一次,digit总会多1。
建议改成while do.
if ((ch>='a')&&(ch<='z')||(ch>='A')&&(ch<='Z'))这里的
(ch>='a')&&(ch<='z')和(ch>='A')&&(ch<='Z')应该分别用括号括起来,不然系统会先执行与再执行或再执行与。
else if (ch>='0'&&ch<='9')
digit++;
else if (ch==' ')