C++ 测试案例
infinity()
#include <iostream>
#include <limits>
int main() {
double inf = std::numeric_limits<double>::infinity();
std::cout << "Infinity (double): " << inf << std::endl;
// 可以用来与其他值进行比较
if (inf > 1000000) {
std::cout << "Infinity is greater than 1 million!" << std::endl;
}
return 0;
}
# g++ testInf.cpp -o testInf
# ./testInf
Infinity (double): inf
Infinity is greater than 1 million!
nextafter
# cat nextafter.cpp
#include <iostream>
#include <cmath>
#include <limits>
#include <iomanip>
template <typename TNum>
TNum roundToDecimals(TNum number, int decimals) {
// 计算放大倍数
long double factor = std::pow(10.0L, static_cast<long double>(decimals));
// 定义正无穷
static const TNum kInf = std::numeric_limits<TNum>::infinity();
// 如果 number 是负数
if (number < 0) {
return static_cast<TNum>(std::round(std::nextafter(number, -kInf) * factor) / factor);
}
// 如果 number 是正数
return static_cast<TNum>(std::round(std::nextafter(number, kInf) * factor) / factor);
}
int main() {
// 测试数据
double number1 = 194.71512499999997;
int decimals1 = 5;
double number2 = -194.71512499999997;
int decimals2 = 5;
// 调用四舍五入函数并输出结果
std::cout << std::setprecision(8) << "Rounded value of " << number1 << " to " << decimals1 << " decimals: "
<< roundToDecimals(number1, decimals1) << std::endl;
std::cout << std::setprecision(8) << "Rounded value of " << number2 << " to " << decimals2 << " decimals: "
<< roundToDecimals(number2, decimals2) << std::endl;
return 0;
}
# ./nextafter
Rounded value of 194.71512 to 5 decimals: 194.71513
Rounded value of -194.71512 to 5 decimals: -194.71513
测试 nextafter
long double factor = std::pow(10.0L, static_cast<long double>(decimals1));
static const double kInf = std::numeric_limits<double>::infinity();
std::cout << std::setprecision(15) << "std::nextafter(number, kInf)" << std::nextafter(number1, kInf) << std::endl;
# ./nextafterdebug
std::nextafter(number, kInf)194.715125
Rounded value of 194.71512 to 5 decimals: 194.71513