std::round 是 C++11 起提供的四舍五入函数,对“.5”采用远离零取整(如 round(2.5)==3.0),非银行家舍入;需包含,返回浮点类型,转 int 时须显式 static_cast 并检查溢出。
直接说结论:std::round 是 C++11 起标准库提供的四舍五入函数,但它对“.5”这种边界情况采用**远离零取整**(如 round(2.5) == 3.0,round(-2.5) == -3.0),不是传统数学中“偶数法则”的银行家舍入。如果你要严格按小学数学理解的“四舍五入”,std::round 多数情况下可用;但若涉及金融、统计等对 .5 特别敏感的场景,它不满足要求。
std::round 定义在 中,接受 float、double、long double,返回对应浮点类型。它不处理整数溢出 —— 若结果超出目标整型范围(比如转成 int 时值为 3e9),强制转换会引发未定义行为。
#include
int x = round(3.7); —— 编译可能通过但隐式截断风险高;应写成 int x = static_cast(std::round(3.7));
把浮点数四舍五入后存进 int,关键不在 round 本身,而在后续转换是否越界。C++ 没有内置带溢出检查的 round-to-int,需手动防护。
std::round 得到浮点结果std::numeric_limits::min() 和 ::max() 做范围判断double val = 2147483648.0; // 超出 int 最大值 double r = std::round(val); if (r > static_cast(INT_MAX) || r < static_cast (INT_MIN)) { throw std::overflow_error("rounded value out of int range"); } int result = static_cast (r);
标准 std::round 不是银行家舍入。若你需要 round(2.5) → 2、round(3.5) → 4 这种偶数优先策略,得自己写。核心思路:分离整数与小数部分,判断小数是否为 0.5 且整数部分是否为偶数。
std::abs + 符号保存frac == 0.5,应判断 std::abs(frac - 0.5)
std::modf 拆分,比字符串或乘法更可靠double bankers_round(double x) {
if (std::is
nan(x) || std::isinf(x)) return x;
double ipart;
double frac = std::modf(std::abs(x), &ipart);
const double eps = 1e-10;
if (frac < 0.5 - eps) {
return (x >= 0) ? ipart : -ipart;
} else if (frac > 0.5 + eps) {
return (x >= 0) ? ipart + 1 : -(ipart + 1);
} else {
// frac ≈ 0.5 → round to even
long i = static_cast(ipart);
return (x >= 0) ? ((i % 2 == 0) ? ipart : ipart + 1)
: ((i % 2 == 0) ? -ipart : -(ipart + 1));
}
} 最易被忽略的一点:float 只有约 7 位有效数字,像 1234567.5f 在 float 中根本无法精确表示,std::round 接收的是一个已经偏移的值。结果可能完全偏离预期。
double 做中间计算,除非明确内存受限double 类型接收,而非 float
std::setprecision(17) 查看真实值,避免被默认 6 位误导比如:float f = 1.23456789f; 实际存储可能是 1.2345678806304931640625,此时 round(f * 100) 可能不是你想要的 123。