在 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>
#include <cmath> // 包含 floor 函数的头文件
using namespace std;double myRound(double x) {return floor(x + 0.5);
}int main() {double x = 3.6;double result = myRound(x); // 四舍五入cout << "myRound(" << x << ") = " << result << endl;return 0;
}
输出
myRound(3.6) = 4
方法 3:对整数进行四舍五入
如果需要对整数进行四舍五入(例如保留到十位、百位等),可以使用以下方法:
示例代码
#include <iostream>
using namespace std;int roundToNearestTen(int x) {return (x + 5) / 10 * 10; // 四舍五入到十位
}int main() {int x = 36;int result = roundToNearestTen(x); // 四舍五入到十位cout << "roundToNearestTen(" << x << ") = " << result << endl;return 0;
}
输出
roundToNearestTen(36) = 40
方法 4:自定义小数位数四舍五入
如果需要对浮点数保留指定小数位数并进行四舍五入,可以使用以下方法:
示例代码
#include <iostream>
#include <cmath>
using namespace std;double roundToDecimal(double x, int decimalPlaces) {double factor = pow(10, decimalPlaces); // 计算 10^decimalPlacesreturn round(x * factor) / factor; // 四舍五入
}int main() {double x = 3.14159;double result = roundToDecimal(x, 2); // 保留 2 位小数并四舍五入cout << "roundToDecimal(" << x << ", 2) = " << result << endl;return 0;
}
输出
roundToDecimal(3.14159, 2) = 3.14
方法 5:使用 std::setprecision
和 std::fixed
如果只需要在输出时进行四舍五入,可以使用 std::setprecision
和 std::fixed
。
示例代码
#include <iostream>
#include <iomanip> // 包含 setprecision 和 fixed 的头文件
using namespace std;int main() {double x = 3.14159;cout << fixed << setprecision(2) << x << endl; // 保留 2 位小数并四舍五入输出return 0;
}
输出
3.14
总结
方法 | 适用场景 | 优点 | 缺点 |
---|---|---|---|
std::round | 浮点数四舍五入 | 简单、标准库函数 | 需要包含 <cmath> 头文件 |
手动实现 | 浮点数四舍五入 | 不依赖标准库 | 需要手动实现 |
整数四舍五入 | 整数四舍五入到十位、百位等 | 简单、高效 | 仅适用于整数 |
自定义小数位数四舍五入 | 浮点数保留指定小数位数并四舍五入 | 灵活 | 需要计算幂次 |
std::setprecision | 输出时四舍五入 | 简单、直接输出 | 仅适用于输出,不改变原值 |