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

条件中的多个表达式(CC++),第1张

概述我想在执行控制块之前确保所有3个条件都得到相同的答案: #include <iostream>#include <cstdlib>int main(){ ///BUT THIS DOES NOT WORK! if ( (2 + 2) == (1 + 3) == (4 + 0) ){ std::cout << "not executed" << std::en 我想在执行控制块之前确保所有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 -> 1false -> 0

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

总结

以上是内存溢出为你收集整理的条件中的多个表达式(C/C++)全部内容,希望文章能够帮你解决条件中的多个表达式(C/C++)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1220789.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存