(a+b) >>1 是什么意思?
int c = (a+b) >>1
在 C++ 中是什么意思?
What does int c = (a+b) >>1
mean in C++?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
int c = (a+b) >>1
在 C++ 中是什么意思?
What does int c = (a+b) >>1
mean in C++?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(6)
它返回
a
和b
的平均值(向下舍入)。因此,如果a
为 5,b
为 8,则结果为 6。ETA:如果
a
和,则此方法无效b
加起来为负数,例如两者均为负数,或者发生整数溢出。It returns the average of
a
andb
, rounded down. So, ifa
is 5 andb
is 8, then the result is 6.ETA: This method is busted if
a
andb
add up to a negative number, like if both are negative, or if integer overflow occurs.请注意,在解释
a
和b
是什么之前,无法对代码的含义做出任何有意义的解释。即使
a
和b
是内置类型,也要小心无条件声称内置右移相当于除以 2 的错误答案。等价仅成立对于非负值。负值的>>
运算符的行为是实现定义的。换句话说,在没有额外信息的情况下,唯一可以说的是代码计算“和”
a + b
并将其右移1位。我在最后一句中使用了引号,因为在重载运算符+
和>>
的情况下,无法预测它们在做什么。Note, that there can't be any meaningful explanation of what your code means until you explain what
a
andb
are.Even if
a
andb
are of built-in type, beware of the incorrect answers unconditionally claiming that built-in right shift is equivalent to division by 2. The equivalence only holds for non-negative values. The behavior of the>>
operator for negative values is implementation-defined.In other words, without extra information, the only thing that can be said is that the code calculates the "sum"
a + b
and "shifts" it right by 1 bit. I used quotes in the last sentence because in case of overloaded operators+
and>>
there's no way to predict what they are doing.这取决于 c、a 和 b 的类型。如果是int则上面的语句是一样的:
>>
表示右移一位。That depends on the type of c, a and b. If it's int then the above statement is the same as:
>>
means shift right one bit.意思是将A与B相加,然后将结果右移一位。对正整数进行移位通常具有乘以或除以 2^n 的效果,其中 n 是移位的位数。因此,这大致相当于整数数学中的 (a+b)/2(没有余数或小数部分)。
It means to add A to B, then bit-shift the result by one bit to the right. Bit-shifting a positive integer generally has the effect of multiplying or dividing by 2^n where n is the number of bits being shifted. So, this is roughly equivalent to (a+b)/2 in integer math (which has no remainders or fractional parts).
这意味着您将
a
和b
相加,然后将结果右移一位。它等同于:
It means that you add
a
andb
, then shift the result one bit to the right.It's the same as:
如上所述,它是一个利用 C++ 中位移运算符的平均函数(其中存在一些潜在的陷阱)——由于这个问题的存在,这段代码的可读性非常差。帮你的程序员同事一个忙,在编写代码时考虑可读性
As mentioned above, it's an average function utilizing the bit-shift operator in c++ (with some potential pitfalls in it) - by the existence of this question, the readability of this code is quite bad. Do your fellow programmer a favor and think about readability when you write code