Fre*_*abe 18
C标准(C99)提供标准C math.h标头中的函数fmaxf和fminf函数.我首先使用它来找到最大的三个花车,然后检查它是否足够快以满足您的需求:
float max = fmaxf(a, fmaxf(b, c));
float min = fminf(a, fminf(b, c));
Run Code Online (Sandbox Code Playgroud)
天真的解决方案是两个使用两个比较找到最小,然后两个比较找到最大.这是次优的,因为三次比较就足够了(伪代码返回(最小,最大)元组如下):
function minmax(float a, float b, float c): (float, float)
begin
boolean altb = (a < b);
boolean bltc = (b < c);
if altb and bltc then return (a, c);
if not altb and not bltc then return (c, a);
if altb then // Also: c <= b, so b is known to be max
begin
if a < c then return (a, b);
return (c, b);
end
if bltc then // Also: b <= a, so b is known to be min
begin
if a < c then return (b, c);
return (b, a);
end
// Unreachable.
end
Run Code Online (Sandbox Code Playgroud)
(这写得最具可读性,而不是最小化分支数)
这执行2到3次比较.因为有3个,所以不可能只使用2个比较!= 3个浮点数的重新排序和2个比较只能区分4个不同的浮点数.这在问题的决策树上很容易看到.
在实践中,应该依赖于编译器上的这种优化.