【发布时间】:2021-03-03 12:45:58
【问题描述】:
这是代码
int numberofletters(string input)
{
int count = 0;
for(int i = 0, n = strlen(input); i < n; i++)
{
if (65 <= (int) input[i] <= 90 | 97 <= (int) input[i] <= 122)
{
count += 1;
}
else
{
count += 0;
}
}
return count;
}
这是我尝试编译时的错误消息
~/pset2/readability/ $ make readability
clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow readability.c -lcrypt -lcs50 -lm -o readability
readability.c:19:34: error: result of comparison of constant 90 with boolean expression is always true [-Werror,-Wtautological-constant-out-of-range-compare]
if (65 <= (int) input[i] <= 90 | 97 <= (int) input[i] <= 122)
~~~~~~~~~~~~~~~~~~~~ ^ ~~
readability.c:19:63: error: result of comparison of constant 122 with boolean expression is always true [-Werror,-Wtautological-constant-out-of-range-compare]
if (65 <= (int) input[i] <= 90 | 97 <= (int) input[i] <= 122)
~~~~~~~~~~~~~~~~~~~~ ^ ~~~
2 errors generated.
我不明白为什么这会创建一个无限真实的陈述,我正在创建两个单独的有界空间,并说如果字符串 ascii 存在于任何一个之间,然后做其他事情做其他事情......我错过了什么吗?
【问题讨论】:
-
逻辑表达式不能像在 C 中那样链接,逻辑 OR 是
||而不是|最后,使用 char 文字而不是幻数。if (('A' <= input[i] && input[i] <= 'Z') || ('a' <= input[i] && input[i] <= 'z'). -
关于:
int numberofletters(string input)string是如何定义的?注意:string不是 C 中的有效类型。但是,cs50.h头文件将string定义为计算结果为char *的宏。你的程序中是否包含cs50.h? -
关于:
if (65 <= (int) input[i] <= 90 | 97 <= (int) input[i] <= 122)这非常令人困惑,假设使用的是 ASCII 字符集。最好有#include <ctype.h>然后声明变为:if( isalpha( input[i] ) )
标签: c if-statement boolean cs50 inequality