(a+b) >>1 是什么意思?

发布于 2024-09-25 03:12:15 字数 57 浏览 3 评论 0原文

int c = (a+b) >>1 在 C++ 中是什么意思?

What does int c = (a+b) >>1 mean in C++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

傲娇萝莉攻 2024-10-02 03:12:15

它返回 ab 的平均值(向下舍入)。因此,如果 a 为 5,b 为 8,则结果为 6。

ETA:如果 a,则此方法无效b 加起来为负数,例如两者均为负数,或者发生整数溢出。

It returns the average of a and b, rounded down. So, if a is 5 and b is 8, then the result is 6.

ETA: This method is busted if a and b add up to a negative number, like if both are negative, or if integer overflow occurs.

做个ˇ局外人 2024-10-02 03:12:15

请注意,在解释 ab 是什么之前,无法对代码的含义做出任何有意义的解释。

即使 ab 是内置类型,也要小心无条件声称内置右移相当于除以 2 的错误答案。等价仅成立对于非负值。负值的 >> 运算符的行为是实现定义的。

换句话说,在没有额外信息的情况下,唯一可以说的是代码计算“和”a + b并将其右移1位。我在最后一句中使用了引号,因为在重载运算符 +>> 的情况下,无法预测它们在做什么。

Note, that there can't be any meaningful explanation of what your code means until you explain what a and b are.

Even if a and b 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.

柳若烟 2024-10-02 03:12:15

这取决于 c、a 和 b 的类型。如果是int则上面的语句是一样的:

c = (a+b)/2;

>>表示右移一位。

That depends on the type of c, a and b. If it's int then the above statement is the same as:

c = (a+b)/2;

>> means shift right one bit.

姜生凉生 2024-10-02 03:12:15

意思是将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).

独享拥抱 2024-10-02 03:12:15

这意味着您将 ab 相加,然后将结果右移一位。

它等同于:

int c = (a + b) / 2;

It means that you add a and b, then shift the result one bit to the right.

It's the same as:

int c = (a + b) / 2;
弥枳 2024-10-02 03:12:15

如上所述,它是一个利用 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文