酷代码 AI
菜单
服务商
DeepSeek字节豆包
更多选项

C++实现:统计n个小数四舍五入与向上/向下取整相等的个数

根据你的需求,这是一个C++程序,实现输入n个小数,分别进行四舍五入,统计四舍五入结果与向上取整和向下取整相等的个数。 ```cpp #include <iostream> #include <cmath> using namespace std; int main() { int n; cin >> n; int roundEqualCeil = 0; // 四舍五入 == 向上取整 int roundEqualFloor = 0; // 四舍五入 == 向下取整 for (int i = 0; i < n; ++i) { double x; cin >> x; double roundVal = round(x); // 四舍五入(.5 向远离零方向) double ceilVal = ceil(x); // 向上取整 double floorVal = floor(x); // 向下取整 if (fabs(roundVal - ceilVal) < 1e-9) { roundEqualCeil++; } if (fabs(roundVal - floorVal) < 1e-9) { roundEqualFloor++; } } cout << roundEqualCeil << " " << roundEqualFloor << endl; return 0; } ``` 代码逻辑: - 使用`round()`进行四舍五入,`ceil()`向上取整,`floor()`向下取整。 - 注意`round()`对.5的处理是远离零方向,例如round(2.5)=3,round(-2.5)=-3。 - 用`fabs`比较浮点数差异,避免精度问题。 - 统计两种情况的数量,按顺序输出。 如果要求更严格遵循“四舍五入”为“四舍五入到最近整数,.5向上取整”(常见业务规则),可将round替换为`floor(x + 0.5)`,但原题未特别说明,一般使用`round()`即可。 ######[AI问答 | 445点数解答 | 2026-08-20 21:46:15]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]