加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

条件中的多个表达式(C/C++)

发布时间:2020-12-16 10:31:15 所属栏目:百科 来源:网络整理
导读:我想在执行控制块之前确保所有3个条件都得到相同的答案: #include iostream#include cstdlibint main(){ ///BUT THIS DOES NOT WORK! if ( (2 + 2) == (1 + 3) == (4 + 0) ){ std::cout "not executed" std::endl; } return EXIT_SUCCESS;} 假设这些数字实
我想在执行控制块之前确保所有3个条件都得到相同的答案:

#include <iostream>
#include <cstdlib>

int main(){

    ///BUT THIS DOES NOT WORK!
    if ( (2 + 2) == (1 + 3) == (4 + 0) ){
        std::cout << "not executed" << std::endl;
    }

    return EXIT_SUCCESS;
}

假设这些数字实际上是变量.这就是我要做的事情:

#include <iostream>
#include <cstdlib>

int main(){

    int n1 = 2;
    int n2 = 2;
    int n3 = 1;
    int n4 = 3;
    int n5 = 4;
    int n6 = 0;

    int a = n1 + n2;

    ///this works
    if ( (n3 + n4) == a && (n5 + n6) == a){
        std::cout << "executed!" << std::endl;
    }

    return EXIT_SUCCESS;
}

问题:为什么我的第一个例子不起作用?

我可以像这样为多个变量分配相同的值:

#include <iostream>
#include <cstdlib>

int main(){

    int a,b,c,d;
    a=b=c=d=9;

    ///prints: 9999
    std::cout <<a<<b<<c<<d<<'n';

    return EXIT_SUCCESS;
}

希望有人能解释为什么这种评估方法不起作用.
在编写if语句时,最近引起了我的注意,该语句确定nxn数组是否是魔方.

解决方法

(2 2)==(1 3)==(4 0)

首先,(2 2)==(1 3)计算结果为真,因为它确实认为4 == 4.

然后,你要比较真==(4 0).在这种情况下,布尔值将转换为整数:

true -> 1
false -> 0

因此你比较1 == 4,结果是假的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读