源代码:
#include//头文件
int main()//主函数
{
int total();
char str[45];
gets(str);
total(str);
return 0;
}
int total(char str[])
{
int number = 0, letter = 0, space = 0, other = 0;
int i;
char a;
for (i = 0; i <= strlen(str); i++)
{
a = str[i];
if (0 <= a <= 9)
number++;
else if (a == ' ' && a != '/n')
space++;
else if ('a' <= a <= 'z' || 'A' <= a <= 'Z')
letter++;
else
other++;
}
printf("字母有%d个\n数字有%d个\n其他有%d个\n空格有%d个\n", letter, number, other, space);
}
运行结果不对
if (0 <= a <= 9)
比较函数中这种写法是有问题的,c语言并不支持连等或者连着的大于小于比较,正确办法应该是
if(a>=0 && a<=9)
&&是逻辑与操作符,只有同时满足a>=0和a<=9才为真。同样的,else if中的判断也是有问题的
//else if ('a' <= a <= 'z' || 'A' <= a <= 'Z')//错误
else if ( (a >= 'a' && a <= 'z' ) || ( a >= 'A' && a <= 'Z'))//正确写法
还有一个小问题,换行符应该是\n
而不是/n
如果对你有帮助,还请点个采纳,万分感谢!
0<=a<=9这种写法有问题的