if语句不适用于||(或)

if statement does not work with || (or)

本文关键字:适用于 语句 不适用 if      更新时间:2023-10-16

我是c的新手++我正试着写一个程序,但我发现它有问题即使在我使用了一个更简单的程序(下面)之后,我也无法理解

当我输入诸如85或55之类的数字时,即使程序不应该响应,它也会进行

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int a=0;
    cin >> a;
    if(a<25 || 30<a<50 || 60<a<75)
    {
        cout << "see it does't workn";
    }
    return 0;
}

请帮我

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int a=0;
    cin >> a;
    if(a<25 || (30<a && a<50) || (60<a && a<75))
    {
        cout << "see it does't workn";
    }
    return 0;
}

您的条件应该是:

if(a<25 || (30<a && a<50) || (60<a && a<75))
{
    cout << "see it does't workn";
}

您的if语句格式不正确。

每个表达式的计算结果必须为true或false,并且不能执行上/下边界之类的操作。

试试这个:

int main()
{
    int a=0;
    cin >> a;
    if(a<25 || (a > 30 && a < 50)  || (a> 60 && a <75))
    {
        cout << "see it does't workn";
    }
    return 0;
}

尝试

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int a=0;
    cin >> a;
    if ((a<25) || ((30<a) && (a<50)) || ((60<a) && (a<75)))
    {
        cout << "see it does't workn";
    }
    return 0;
}

圆括号是你的朋友。每个二进制条件表达式将具有左部分(a)、运算符(<)和右部分(25)。你必须把每件事都分解才能用这种方式表达出来。

下面的if语句中发生了什么:

if(a<25 || 30<a<50 || 60<a<75)

当a=85时,30总是小于a,因此为真(当转换为整数时,意味着c++中的1),然后1总是小于50,因此为true。

因此,考虑将if语句更改为

if ( a < 25 || (30 < a && a < 50) || ( 60 < a && a < 75) )

C++中没有x < z < y类型的语句。您应该将这些语句分成二进制部分:x < z && z < y

让我为你重写一下:

#include <iostream>
int main() {
    int a = 0;
    std::cin >> a;
    if(a < 25 || (30 < a && a < 50) || (60 < a && a < 75)) {
        std::cout << "See? It does work!n";
    }
    return 0;
}