本题要求编写程序,输入一行字符,统计其中数字字符、空格和其他字符的个数。建议使用switch语句编写。
输入格式:
输入在一行中给出若干字符,最后一个回车表示输入结束,不算在内。
这样为什么不可以
#include
int main(void)
{
int a=0;int b=0;int c=0;
char ch;
scanf("%c",ch);
while(ch!='\n')
{
switch(ch)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
a++;
break;
case ' ':
b++;
break;
default:
c++;
break;
}
scanf("%c",ch);
}
printf("blank = %d, digit = %d, other = %d",b,a,c);
return 0;
}
就是你写的程序,运行出结果的时间超出题目给的时间限制。
你写得程序中,那个while那里,等号是==,不是=,你这样不死循环才怪。
你写的scanf是不是也得放在循环中?你放在外面只输入了一个字符
供参考:
#include<stdio.h>
int main(void)
{
int a=0, b=0, c=0, i=0; //修改
char ch[128]; //修改
gets(ch); //scanf("%c",ch); 修改
while(ch[i] != '\0') //while(ch!='\n') 修改
{
switch(ch[i])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
a++;
break;
case ' ':
b++;
break;
default:
c++;
break;
}
i++; //scanf("%c",ch); 修改
}
printf("blank = %d, digit = %d, other = %d",b,a,c);
return 0;
}