首页 > 解决方案 > 当我尝试编译这个 C 代码时,我得到一个无限的 true bool 错误,我不知道为什么

问题描述

这是代码

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 存在于任何一个之间,那么做其他事情做其他事情......我错过了什么吗?

标签: cif-statementbooleancs50inequality

解决方案


这没有做你认为它正在做的事情:

65 <= (int) input[i] <= 90 

此表达式不测试是否input[i]介于 65 和 90 之间。它实际上解析为:

(65 <= (int) input[i]) <= 90 

所以它首先检查是否input[i]大于或等于 65。这将导致值 0 或 1。所以现在你有这个:

1 <= 90

或这个:

0 <= 90

两者都是正确的,这就是您收到该警告的原因。

您需要分别执行每项检查:

 if ((65 <= input[i] && input[i] <= 90) || (97 <= input[i] && input[i] <= 122))

更好的是,摆脱幻数并使用字符常量:

 if (('A' <= input[i] && input[i] <= 'Z') || ('a' <= input[i] && input[i] <= 'z'))

甚至更好:

if (isalpha(input[i]))

推荐阅读