Use std::round()
as commented by @Revolver_Ocelot
Using floor(x + 0.5)
has cases where it fails:
Negative numbers. Of course code could attempt ceil(x - 0.5)
for that.
Cases where the sum x+0.5
may create a rounded answer that is a new integer: The FP number just less than 0.5. Some values where the ULP (the least signification binary digit) of x
is 0.5 or 1.0.
IOWs, code needs to insure a 0.5
addition does not require extra precision.
Below is a candidate round_alt()
should round()
not exist. round_alt()
does not have these problems.
double round_alt(double x) {
double ipart;
// break into integer and fraction parts
double fpart = modf(x, &ipart);
if (fpart != 0.0) {
if (x >= 0.5) {
ipart += floor(fpart + 0.5);
} else if (x <= -0.5) {
ipart += ceil(fpart - 0.5);
}
}
return ipart;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…