Tre*_*key 3 c c++ boolean-logic expression conditional-statements
我想在执行控制块之前确保所有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;
}
Run Code Online (Sandbox Code Playgroud)
假设这些数字实际上是变量.这就是我要做的事情:
#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;
}
Run Code Online (Sandbox Code Playgroud)
问题:为什么我的第一个例子不起作用?
我可以像这样为多个变量分配相同的值:
#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;
}
Run Code Online (Sandbox Code Playgroud)
希望有人能解释为什么这种评估方法不起作用.
在编写if语句时,最近引起了我的注意,该语句确定nxn数组是否是魔方.
Imp*_*Imp 12
(2 + 2) == (1 + 3) == (4 + 0)
首先,(2 + 2) == (1 + 3)
评估true
,因为它确实持有4 == 4
.
然后,你要比较true == (4 + 0)
.在这种情况下,布尔值将转换为整数:
true -> 1
false -> 0
Run Code Online (Sandbox Code Playgroud)
因此,你在比较1 == 4
,结果是错误的.
归档时间: |
|
查看次数: |
1386 次 |
最近记录: |