C语言中长久的数学运算 [英] Math operations with long long in c
问题描述
给出 long long x
, long long y
和 int z
,如何截断(( x
+ y
+ z
)/3)是在C语言中使用完全定义的运算来计算的,但不包括 unsigned long long
和更宽泛的算术运算吗?
Given long long x
, long long y
, and int z
, how can trunc((x
+y
+z
)/3) be calculated using fully defined operations in C but excluding unsigned long long
and wider arithmetic?
(trunc( x )向零舍入":如果 x 是整数,则为 x ,否则为下一个整数趋近于零.)
(trunc(x) is "rounding toward zero": It is x if x is an integer and otherwise is the next integer toward zero.)
推荐答案
您可以计算两个整数 x
和 y
的平均值,而不会出现溢出风险,如下所示(伪代码):
You can calculate the average of two integers x
and y
without the risk of overflow as follows (pseudocode):
int average = (x and y have the same sign)
? x + (y - x) / 2
: (x + y) / 2;
由于整数截断,这是不对称的.如果您想始终舍入为0,则需要做一些更复杂的事情:
This is not symmetric due to integer truncation. If you want to always round towards 0, you need to do something slightly more complicated:
int average = (x and y have the same sign)
? (x and y are both even or both odd)
? x + (y - x) / 2
: x + (y - x - sgn(x)) / 2
: (x + y) / 2;
其中 sgn
是符号函数(-1、0或+1,具体取决于参数是负数,零还是正数). sgn(x)
的实现很多,但是一个不错的实现是:(x> 0)-(x< 0)
.
where sgn
is the signum function (-1, 0, or +1 depending on whether the argument is negative, zero, or positive). There are lots of implementations of sgn(x)
, but one nice one is: (x > 0) - (x < 0)
.
如果您想始终四舍五入...则留作练习.:)
If you want to always round down...that's left as an exercise. :)
这篇关于C语言中长久的数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!