https://blog.csdn.net/Xavier_97/article/details/126931927

由于很玄学,我们考虑统一使用库函数round和自己手写round来实现最终输出整数的四舍五入小数保留k位的四舍五入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double a = 1.4999999;
double b = 1.5000001;
double n_a = -1.4999999;
double n_b = -1.5000001;
cout << round(a) << endl; // 1
cout << round(b) << endl; // 2
cout << round(n_a) << endl; // -1
cout << round(n_b) << endl; // -2
return 0;
}

要得到四舍五入小数点后的结果,我们可以将小数转换为整数来处理,然后再转换为小数。

  • 例如我们需要将1.2345这个数保留小数点后两位四舍五入,我们可以先将其乘以100转换为123.45,然后套用整数的方法来进行四舍五入,再将其除以100转换为小数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

using namespace std;

// 用于四舍五入
int round_0 (double n)
{
// 若为负数,则先化为正数再进行四舍五入
if (n > 0)
return n - int(n) >= 0.5 ? int(n)+1 : int(n);
else
return -n - int(-n) >= 0.5 ? -(int(-n) + 1) : -int(-n);
}

int main()
{
double a = 1.2345;
double b = 1.2355;
double n_a = -1.2345;
double n_b = -1.2355;

a = round_0(a * 100.0) / 100.0;
b = round_0(b * 100.0) / 100.0;
n_a = round_0(n_a * 100.0) / 100.0;
n_b = round_0(n_b * 100.0) / 100.0;

cout << a << endl; // 1.23
cout << b << endl; // 1.24
cout << n_a << endl; //-1.23
cout << n_b << endl; // -1.24
return 0;
}