首页 > 试题广场 >

下面程序有什么错误? #include int

[问答题]
下面程序有什么错误?
#include <stdio.h>
int main (void)
{
char ch;
int 1c = 0;           /* 统计小写字符
int uc = 0;           /* 统计大写字符
int oc = 0;           /* 统计其他字符
while ((ch = getchar ( )) != '#')
{
if ('a' <= ch >= 'z')
1c++;
else if (! (ch < 'A') l l ! (ch > 'Z')
uc++;
oc++;
}
printf (%d lowercase, %d uppercase, %d other, 1c, uc, oc);
return 0;
}

推荐
第5行到第7行的注释应该以*/结尾,或者用//来代替/*。表达式'a'<=ch>='z'应该被写成这样:ch >= 'a' && ch <= 'z'
或者用一种更简单也更通用的方法:包含ctype.h文件并使用islower()。顺便提一下,'a'<=ch>='z'在C中是合法的,只是不具有正确的意义。因为关系运算符是从左到右结合的,所以这个表达式被解释为('a'<=ch) >='z'。圆括号中表达式的值为1或0(真或假),然后检查这个值来看它是否等于或大于'z'的数值编码。0和1都不能满足这个条件,所以整个表达式的值总是为0(假)。在第二个判断表达式中,ll应该是&&。尽管!(ch<'A')是合法的,而且意义也正确,但ch>='A'更为简单。'Z'后面需要有两个结束圆括号而不是一个。再一次,更简单的方法是使用isupper()。应该在oc++;语句前面放置一个else,否则,每输入一个字符,它都会增加1。在printf()调用中的控制表达式应该用双引号引起来。
下面是正确的版本:
#include <stdio.h>
#include <ctype.h>
int main (void)
{
char ch;
int 1c = 0;   /* 统计小写字符 */
int uc = 0    /* 统计大写字符 */
int oc = 0;   /* 统计其他字符 */
while ((ch = getchar ( )) != '#')
{
if (islower (ch))
1c++;
else if (isupper (ch))
uc++;
else
oc++;
}
printf ("%d lowercase, %d uppercase, %d other", 1c, uc, oc);
return 0;
}

发表于 2018-03-23 22:03:04 回复(1)
输出类型加引号,主函数不加参数
发表于 2018-04-17 19:15:32 回复(0)