如何在 C++ 中将双精度数四舍五入到整数上

本文将为大家讲解几种在 C++ 中如何将双精度数四舍五入为整数的方法。

使用 round() 函数将双精度数四舍五入到整数

round() 函数在 <cmath> 头中定义。它可以计算用户传递的参数的最接近的整数值。半数情况下会从零开始四舍五入,并且返回的值与参数的类型相同。在下面的例子中,我们初始化一个任意的双精度数向量,并为每个元素输出 round() 函数。

#include <cmath>#include <iostream>#include <vector>using std::cout;
using std::endl;
using std::vector;
int main() {
    vector<double> dfloats {-3.5, -21.1, -1.99, 0.129, 2.5, 3.111};
    for (auto &item : dfloats) {
        cout << "round(" << item << ") = " << round(item) << endl;
    }
    return EXIT_SUCCESS;
}

输出:

round(-3.5) = -4
round(-21.1) = -21
round(-1.99) = -2
round(0.129) = 0
round(2.5) = 3
round(3.111) = 3

使用 lround() 函数将双精度数转换为最接近的整数

或者,我们可以使用 lround() 函数,它的行为与 round() 几乎相同,但有一点不同:它以 long 整数格式返回值。需要注意的是,对于这两个函数来说,返回值可能会出乎意料,这是由普遍存在的不同舍入误差引起的。应按照文档中的规定进行处理。

#include <cmath>#include <iostream>#include <vector>using std::cout;
using std::endl;
using std::vector;
int main() {
    vector<double> dfloats {-3.5, -21.1, -1.99, 0.129, 2.5, 3.111};
    for (auto &item : dfloats) {
        cout << "round(" << item << ") = " << lround(item) << endl;
    }
    return EXIT_SUCCESS;
}

使用 trunc() 函数双精度数四舍五入到整数

trunc()<cmath> 头文件中的另一个有用的函数,它计算不大于作为参数传递的数字的最近的整数。trunc()round() 一样,以浮点格式计算返回值。注意,这两个函数不会对当前的四舍五入模式产生任何影响。错误处理情况在手册页中描述。

#include <cmath>#include <iostream>#include <vector>using std::cout;
using std::endl;
using std::vector;
int main() {
    vector<double> dfloats {-3.5, -21.1, -1.99, 0.129, 2.5, 3.111};
    for (auto &item : dfloats) {
        cout << "round(" << item << ") = " << trunc(item) << endl;
    }
    return EXIT_SUCCESS;
}
round(-3.5) = -3
round(-21.1) = -21
round(-1.99) = -1
round(0.129) = 0
round(2.5) = 2
round(3.111) = 3