结果总是0吗?说明

时间:2014-09-24 03:24:06

标签: c

初学者C(系统)

include <stdio.h>
int main() {

int n1 = -1;
int n2 = 2;

unsigned int u1 = (unsigned int) n1;
unsigned int u2 = (unsigned int) n2;


int result = (n1 < n2) == (-n1 > -n2);
print f("(%d < %d) == (-%d > -%d) evaluates to %d\n", n1, n2, n1, n2, result);


/*question 1 
Is result always 1 (true)?
*/

result = ~n1 + ~n2 == ~(n1 + n2);
printf("(~%d + ~%d) == ~(%d + %d) evaluates to %d\n", n1, n2, n1, n2, result);

return 0;

/*question 1 
Is result always 0(false)?
*/
}

我不知道#1想要展示的概念,但我认为#2基本上会询问是否存在〜分发的情况。

1 个答案:

答案 0 :(得分:0)

如果您将有效不等式的两边乘以负数,则必须reverse the order of the inequality才能使其有效:

(a < b)*-1 -> (-1*a > -1*b)

因此对于问题1,result总是 true 或1:

int result = (n1 < n2) == (-n1 > -n2);

如果n1小于n2,则-n1将始终大于-n2,因此对于该情况,相等性测试为真。

如果n1不小于n2,那么-n1将不会大于-n2,因此对于该情况,相等性测试也是如此。因此,平等测试总是正确的。