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

C++ 实现对输入小数四舍五入与上下取整结果统计

以下是实现上述功能的 C++ 代码: ```cpp #include <iostream> #include <iomanip> #include <cmath> int main() { int n; std::cin >> n; int ceilingCount = 0; int floorCount = 0; for (int i = 0; i < n; ++i) { double num; std::cin >> num; // 四舍五入的结果 int rounded = static_cast<int>(std::round(num)); // 向上取整的结果 int ceilingResult = static_cast<int>(std::ceil(num)); // 向下取整的结果 int floorResult = static_cast<int>(std::floor(num)); // 判断四舍五入结果是否和向上取整结果相等 if (rounded == ceilingResult) { ceilingCount++; } // 判断四舍五入结果是否和向下取整结果相等 if (rounded == floorResult) { floorCount++; } } std::cout << ceilingCount << " " << floorCount << std::endl; return 0; } ``` ### 代码解释: 1. **输入处理**:首先从标准输入读取一个正整数 `n`,表示后续要输入的小数的个数。 2. **初始化计数器**:创建两个变量 `ceilingCount` 和 `floorCount`,分别用于记录四舍五入结果与向上取整结果相等的个数和四舍五入结果与向下取整结果相等的个数。 3. **循环读取小数**:使用 `for` 循环 `n` 次,每次读取一个小数。 4. **计算相关结果**:对于每个读取的小数,使用 `std::round` 函数计算四舍五入的结果,使用 `std::ceil` 函数计算向上取整的结果,使用 `std::floor` 函数计算向下取整的结果。 5. **更新计数器**:比较四舍五入结果与向上取整结果,如果相等则 `ceilingCount` 加 1;比较四舍五入结果与向下取整结果,如果相等则 `floorCount` 加 1。 6. **输出结果**:循环结束后,输出 `ceilingCount` 和 `floorCount` 的值。 ######[AI问答 | 550点数解答 | 2026-07-18 20:13:37]

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