举两个有符号数的C中的平均 [英] Take the average of two signed numbers in C

查看:206
本文介绍了举两个有符号数的C中的平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说,我们必须用C x和y无一不是有符号整数,我们如何在两者之间找到最精确的平均值?

我想preFER不采取任何机/编译器/工具链运作的特定优势的解决方案。

我想出了是最好的:(A / 2)+(B / 2)+ !!(%2)* !!(B%2)是否有一个解决方案,更准确?更快?简单?

如果我们知道什么,如果一个比另一个更大的先验

感谢。

D


编者按:请注意,OP预计,不受整数当输入值接近到C INT 类型。这是不是在原来的问题说,但给一个答案的时候是很重要的。


解决方案

  A / 2 + B / 2 +(%2 + B%)/ 2

似乎最简单的一个装配实施特性(它的C99其中指定的结果的相关性/为截断向0,而它的实现依赖于C90)。

没有假设的法案

它不具有测试(因此不昂贵的跳跃),并且所有司/剩余部分的优点是由2所以由编译器的使用位摆弄技术是可能的。

Let us say we have x and y and both are signed integers in C, how do we find the most accurate mean value between the two?

I would prefer a solution that does not take advantage of any machine/compiler/toolchain specific workings.

The best I have come up with is:(a / 2) + (b / 2) + !!(a % 2) * !!(b %2) Is there a solution that is more accurate? Faster? Simpler?

What if we know if one is larger than the other a priori?

Thanks.

D


Editor's Note: Please note that the OP expects answers that are not subject to integer overflow when input values are close to the maximum absolute bounds of the C int type. This was not stated in the original question, but is important when giving an answer.

解决方案

a/2 + b/2 + (a%2 + b%2)/2

Seems the simplest one fitting the bill of no assumption on implementation characteristics (it has a dependency on C99 which specifying the result of / as "truncated toward 0" while it was implementation dependent for C90).

It has the advantage of having no test (and thus no costly jumps) and all divisions/remainder are by 2 so the use of bit twiddling techniques by the compiler is possible.

这篇关于举两个有符号数的C中的平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆