舍入程序
Rounding Program
我需要使用C++
对一些输入数字进行四舍五入。下面是我的代码
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int a;
int b;
int c;
cin >> a;
for (int i =0; i<a; i++) {
cin >> b;
cin >> c;
int result = b/c;
if (result > 0) {
cout << floor(result + 0.5) << " ";
} else {
cout << ceil(result - 0.5) << " ";
}
}
}
然而,我总是得到过低的答案。
示例输入:
15
6525 1410
14431 510
9163 480
5461 1938
6969 1220
-7065150 -4171886
-9268414 -1461265
17913 584
-32381 -634679
19887 1666
5133363 4488942
5440267 601
4700414 923
4699610 15
4322342 201
输出:4 28 19 2 5 1 6 30 -0 11 1 9052 5092 313307 21504
预期:5 28 19 3 6 2 6 31 0 12 1 9052 5093 313307 21504
我做错了什么?(为什么我在其中一个上得到了负零?)
您在int中进行除法,而不是在float中。你可以这样做来修复:
double result = static_cast<double>(b)/c;
并且对于0的值最好也使用floor以避免负零,即
if (result >= 0.0) {
另一个问题,除了像另一个答案所指出的那样将除法作为整数除法之外,还应该使用std::round(3)。手动加法/减法.5很容易出现舍入错误,当std::round
为您完成任务时,没有理由重新发明轮子。
相关文章:
- C++将浮点指针值舍入为小数位数
- Boost::posix_time::ptime舍入到给定的分钟数
- 浮点定向舍入和优化
- 为什么输出精度没有正确舍入?
- 使用设置精度时如何阻止数字向上舍入?
- 如何在使用 MPFR 时在提升多精度中设置舍入模式
- OpenCV 细分一致的 Rect2f 到 Rect2i 舍入
- C++ 中的舍入函数
- 舍入 QDecDouble 值,精度最多为两个字符
- 如何将控制台应用程序放入系统托盘通知C++?
- 将大 int 转换为浮点数,而不舍入 c++
- 舍入错误检测
- 根据浮点符号对浮点进行舍入的最简单方法是什么
- 将整数舍入到另一个整数的最接近的倍数
- Sizeof 舍入到对齐方式,但编译器仍将对象放在剩余的字节中
- 无法弄清楚如何让 CMake 为自定义 clang 驱动程序拉入正确的标头
- 避免将 Int 转换为双重类型转换舍入
- 浮点数学运算后舍入不一致
- 为什么这个C++程序舍入双值而不打印整个字符串
- 舍入程序