封面: C++进行特定位数的四舍五入/向上取整/向下取整/截断

C++进行特定位数的四舍五入/向上取整/向下取整/截断

ZL Asica2022-03-08

我们在C++中有时会需要使用到数学运算,同样的可能会使用到标题提到的几种方式进行运算。实际上C++有一个库<cmath>可以直接实现这些方法操作。

CPP
1#include <cmath> 2 3int main() 4{ 5 double a = 43.5555; 6 7 // 四舍五入 8 a = std::round(a); 9 std::cout << a << std::endl; // 44.0000 10 11 // 向下取整 12 a = std::floor(a); 13 std::cout << a << std::endl; // 43.0000 14 15 // 向上取整 16 a = std::ceil(a); 17 std::cout << a << std::endl; // 44.0000 18 19 // 截断 20 a = std::trunc(a); 21 std::cout << a << std::endl; // 43.0000 22 23 return 0; 24}

那么这就是最简单的四种算法在C++中的使用了。

那么有时候我们进行这样的数学运算后,目的就是为了得到一个更方便看的数,那当然要取特定位数的小数了。写法规则如下(以四舍五入方法std::round做演示)。

CPP
1 a = std::round(a * 保留到几分位) / 保留到几分位; // 保留到十分位 = 保留两位小数

我们来一个保存两位小数(十分位)的实例来看一下。

CPP
1#include <iostream> 2#include <cmath> 3 4int main() 5{ 6 double a = 43.5555; 7 a = std::round(a * 10) / 10; 8 std::cout << a << std::endl; 9 10 return 0; 11}

那么这样就可以非常轻松的在C++中获取到我们需要的小数位数了。

我们上面说到了如何获取到特定的位数,但是这样获取到的还是double值,如果想要和std::string一起操作是会出现问题的。如果我们想要把这个double和其他的string放到一起的话,我们就需要按照如下代码进行操作。

CPP
1#include <iostream> 2#include <cmath> 3#include <string> 4 5int main() 6{ 7 double a = 43.5555; 8 a = std::round(a * 10) / 10; 9 // 先转换为std::string类型 10 std::string tempre = std::to_string(a); 11 // 对std::string类型进行10位小数的格式化(下面语句会输出10位小数) 12 std::cout << tempre.substr(0, tempre.find(".") + 2) << std::endl; 13 14 return 0; 15}

这就是本文的全部内容了。

Creative Commons Logo

本文作者:ZL Asica

本文标题:C++进行特定位数的四舍五入/向上取整/向下取整/截断

本文链接:https://www.zla.pub/cpp-round

本文采用 CC BY-SA 4.0 Deed 进行许可