在 C++ 中,可以通过以下几种方法快速实现 四舍五入:
方法 1:使用 std::round 函数
std::round 是 C++ 标准库 <cmath> 中的一个函数,用于对浮点数进行四舍五入。
示例代码
#include <iostream>
#include <cmath> // 包含 round 函数的头文件
using namespace std;
int main() {
double x = 3.6;
double result = round(x); // 四舍五入
cout << "round(" << x << ") = " << result << endl;
return 0;
}
输出
round(3.6) = 4
方法 2:手动实现四舍五入
如果不想使用标准库函数,可以通过以下公式手动实现四舍五入:
[
\text{rounded} = \text{floor}(x + 0.5)
]
其中,floor 是向下取整函数。
示例代码
#include <iostream>
#</


1744

被折叠的 条评论
为什么被折叠?



