直接赋值截断小数,round()实现四舍五入,floor/ceil向下向上取整,加0.5法仅适用正数。推荐使用std::round()。

在C++中,将double类型转换为int时,直接赋值会截断小数部分(即向零取整),但实际开发中我们常常需要四舍五入或其他取整方式。以下是几种常用方法。
将double直接赋给int变量时,编译器会自动截断小数部分,只保留整数部分。
double d = 3.7; int i = d; // i = 3 double d2 = -3.7; int i2 = d2; // i2 = -3(向零取整)
这种方式不是四舍五入,而是简单地去掉小数部分。
C++标准库<cmath>提供了round()函数,可实现数学上的四舍五入。
立即学习“C++免费学习笔记(深入)”;
#include <cmath> double d = 3.7; int i = static_cast<int>(round(d)); // i = 4 double d2 = -3.7; int i2 = static_cast<int>(round(d2)); // i2 = -4
注意:返回值是double,需显式转为int。
<cmath>还提供以下函数:
floor(x):向下取整(向负无穷)ceil(x):向上取整(向正无穷)#include <cmath> double d = 3.2; int a = static_cast<int>(floor(d)); // 3 int b = static_cast<int>(ceil(d)); // 4
对正数可通过加0.5再截断实现四舍五入:
double d = 3.7; int i = static_cast<int>(d + 0.5); // i = 4
注意:此法对负数不适用。例如-3.7 + 0.5 = -3.2,转为int得-3,不符合四舍五入规则。若需支持负数,应使用round()。
基本上就这些常见方法。推荐优先使用std::round(),简洁且符合标准。手动加0.5适合简单场景,但要注意符号问题。
以上就是C++如何将double转int_C++浮点数取整与四舍五入方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号