[英]Can someone help me to understand output of this code
Hello beautiful people, I need a help with output of this program: 您好美女,我需要有关此程序输出的帮助:
#include <stdio.h>
int main() {
int x,y;
scanf("%d %d",&x,&y);
int t = x^y;
int p = 0;
while (t > 0) {
p += t%2;
t /= 2;
}
printf("%d", p);
return 0;
}
I tried to write it down on paper and do some work by hand. 我试图将其写下来,然后手工做一些工作。 So i wrote this :
所以我写了这个:
lets say for x = 2 and y = 4 假设x = 2和y = 4
first iteration: 第一次迭代:
p = 0 + 16mod2 which is equal to 0 p = 0 + 16mod2等于0
t = 8 t = 8
second iteration: 第二次迭代:
p = 0 + 8mod2 which is equal to 0 p = 0 + 8mod2等于0
t = 4 t = 4
third iteration: 第三次迭代:
p = 0 + 4mod2 which is equal to 0 p = 0 + 4mod2等于0
t = 2 t = 2
forth iteration: 第四次迭代:
p = 0 + 2mod2 which is equal to 0 p = 0 + 2mod2等于0
t = 1 t = 1
And output should be 0, but somehow when I run code I get 2. Can someone help me out with this one please? 输出应该为0,但是以某种方式运行代码时我得到2。有人可以帮我解决这个问题吗? And are there any other cases to consider, like what if x = 0, y = 0 or x and y are < 0 ?
还有其他需要考虑的情况,例如x = 0,y = 0或x和y <0时该怎么办?
The problem here, is that you assume that 2^4 == 16
, when in fact, it is only 6
, as the ^
operator, is actually an XOR
. 这里的问题是,您假设
2^4 == 16
,而实际上只有6
,作为^
运算符,实际上是XOR
。
You should be using 您应该使用
int t = pow(x, y)
int t = x^y;
Is not " x
raised to the power of y
". 不是“
x
提高到y
的幂”。 It's " x
XOR y
". 是“
x
XOR y
”。 T starts at 6 in your example. 在您的示例中,T从6开始。
As others have mentioned x^y is XOR
operation, what you had in mind is : 正如其他人提到的x ^ y是
XOR
运算一样,您想到的是:
#include <math.h>
....
int t = pow(x,y);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.