如何计算 unsigned char 数组中元素的平均值?
我有一个快速的问题,但我在网上找不到任何东西。
如何计算 unsigned char 数组中元素的平均值? 或者更类似的是,对无符号字符执行操作?
I've got a quick and I am assuming question but I have not been able to find anything online.
How to calculates the average of elements in an unsigned char array?
Or more like it, perform operations on an unsigned char?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C++03 和 C++0x:
在线演示:http://www.ideone.com/2YXaT
仅 C++0x(使用 lambda)
在线演示:http://www.ideone.com/IGfht
C++03 and C++0x:
Online Demo : http://www.ideone.com/2YXaT
C++0x Only (using lambda)
Online Demo : http://www.ideone.com/IGfht
算术运算在
unsigned char
上工作得很好,尽管您有时可能会对 C 中的算术总是提升为int
这一事实感到惊讶。在C++的标准模板库中,
要计算
unsigned char arr[]
的总和,可以使用accumulate(arr, arr + sizeof(arr) / sizeof(arr[0]), 0 )
。 (这里 0 是int
。您可能会发现使用不同的类型更合适。)如果没有 STL,则可以通过循环轻松计算。
平均值是总和除以长度 (
sizeof(arr) / sizeof(arr[0])
)。Arithmetic operations work just fine on
unsigned char
, although you may occasionally be surprised by the fact that arithmetic in C always promotes toint
.In C++'s Standard Template Library,
To calculate the sum of
unsigned char arr[]
, you may useaccumulate(arr, arr + sizeof(arr) / sizeof(arr[0]), 0)
. (0 is anint
here. You may find it more appropriate to use a different type.)Without STL, this is trivially computed with a loop.
The average is the sum divided by the length (
sizeof(arr) / sizeof(arr[0])
).与其他任何事情一样,您将它们相加并除以计数。为了避免溢出,您通常需要在进行数学计算时将它们转换为更大的值。如果(这是常见的)您想要浮点结果,您也需要在浮点上进行所有数学运算。
About like with anything else, you add them up and divide by the count. To avoid overflow, you'll typically want to convert them to something larger while you're doing the math. If (as is common) you want a floating point result, you'll want to do all the math on floating point as well.