蓝色天空.知识 · 实践 · 创造
我的收藏
C++ 教程目录 99章
课程介绍
C++ / LEARN BY DOING

C++ <cmath>

系统梳理 <cmath> 六大类数学函数(基本算术、指数对数、三角、双曲、取整拆分与浮点状态检查),厘清 remainder、rint/nearbyint 与域错误返回 NaN 的标准行为,并在离线 G++ C++17 容器实测。

学完这一章,你能够

  • 系统梳理 <cmath> 六大类数学函数(基本算术、指数对数、三角、双曲、取整拆分与浮点状态检查),厘清 remainder、rint/nearbyint 与域错误返回 NaN 的标准行为,并在离线 G++ C++17 容器实测。

数学库头文件定位与六大函数族

头文件 `<cmath>` 是 C++ 标准库对 C 数学库 `<math.h>` 的封装与重载扩展,涵盖绝对值、幂指对、三角与反三角、双曲、舍入拆分以及 IEEE 754 浮点特殊值判定等常用函数。使用前包含 `#include <cmath>`,建议通过 `std::` 命名空间限定调用以命中 C++ 完整类型重载集。

库内函数按用途可分为六大族:第一族基本算术含 `abs`/`fabs`、`fmod`、`remainder`、`fmax`/`fmin` 与避免中间溢出的斜边函数 `hypot`(注意:`fmod(5.3, 2)` 按向零截断商取余得 `1.3`,而 IEEE 754 `remainder(5.5, 2.0)` 按向最近偶数取整商 `3` 计算 `5.5 - 3*2.0 = -0.5`);第二族指数与对数含 `exp`、`log`、`log10`、`pow`、`sqrt`、`cbrt` 以及在小参数处保持高精度的 `expm1`/`log1p`;第三族与第四族分别为弧度制三角/反三角(含确定象限的 `atan2(y, x)`)和双曲/反双曲函数;第五族取整与拆分包含 `ceil`、`floor`、`trunc`、`round`/`lround`/`llround`(半途远离零舍入,故 `round(2.5)==3`)、遵循当前浮点舍入模式的 `nearbyint`/`rint`(默认 `FE_TONEAREST` 偶数舍入模式下二者对 `2.5` 均返回 `2.0`,区别仅在于 `nearbyint` 不置位 `FE_INEXACT`)及整数小数分离函数 `modf`;第六族浮点状态检查含 `isfinite`、`isinf`、`isnan`、`isnormal` 与 `signbit`。

综合示例与重载、域错误注意事项

典型示例演示了 `sqrt(9.0)`、`sin(pi / 2)`、`abs(-5.0)`、`fmod(5.3, 2)`、`exp(1)`、`pow(2, 3)`、`ceil`/`floor` 以及用 `isinf` 检测无穷大。在严格可移植代码中,获取无穷大与 `NaN` 推荐使用 `<limits>` 的 `std::numeric_limits<double>::infinity()` / `quiet_NaN()`,避免编译期 `1.0 / 0.0` 触发除零告警。

使用 `<cmath>` 时需牢记三点:第一,C++ `<cmath>` 为 `float`、`double`、`long double` 提供了同名重载(同时也保留了源自 C 的 `f`/`l` 后缀版本如 `sqrtf`/`sqrtl`);第二,向 `pow`、`log`、`sqrt` 等函数传入整数实参时,标准库会通过附加模板重载将其隐式提升为 `double` 并返回浮点结果;第三,与部分直觉不同,`<cmath>` 数学函数遇到定义域错误(如 `std::sqrt(-1.0)`)**不会抛出 `std::domain_error` 等 C++ 异常**,而是依 `math_errhandling` 置位 `errno = EDOM` 和/或浮点异常标志并返回 `NaN`,业务代码应以 `std::isnan()` 或 `std::isfinite()` 检验计算结果。本站离线 G++ C++17 实验已实测全部六大族函数与 `sqrt(-1.0)` 返回 `NaN` 的标准行为。

<cmath> 基本数学函数表

函数功能示例
abs(x)计算整数或浮点数的绝对值(C++ <cmath> 重载支持浮点)std::abs(-5) == 5
fabs(x)计算浮点数 x 的绝对值std::fabs(-5.5) == 5.5
fmod(x, y)计算 x / y 的截断浮点余数(与 x 同号)std::fmod(5.3, 2.0) ≈ 1.3
remainder(x, y)计算 IEEE 754 就近偶数商余数(x - n*y)std::remainder(5.5, 2.0) == -0.5
fmax(x, y)返回两个浮点数中的较大值(自动忽略单个 NaN)std::fmax(3.5, 4.2) == 4.2
fmin(x, y)返回两个浮点数中的较小值(自动忽略单个 NaN)std::fmin(3.5, 4.2) == 3.5
hypot(x, y)计算直角边斜边长 sqrt(x² + y²) 且防中间溢出std::hypot(3.0, 4.0) == 5.0

<cmath> 指数、对数与幂根函数表

函数功能示例
exp(x)计算自然指数 e^xstd::exp(1.0) ≈ 2.71828
log(x)计算以 e 为底的自然对数 ln(x)(x > 0)std::log(std::exp(1.0)) == 1.0
log10(x)计算以 10 为底的常用对数(x > 0)std::log10(100.0) == 2.0
pow(x, y)计算 x 的 y 次幂std::pow(2, 3) == 8.0
sqrt(x)计算非负数的平方根(负数返回 NaN)std::sqrt(16.0) == 4.0
cbrt(x)计算实数的立方根(支持负数)std::cbrt(27.0) == 3.0
expm1(x)高精度计算 e^x - 1(避免 x≈0 时的有效数字抵消)std::expm1(1.0) ≈ 1.71828
log1p(x)高精度计算 ln(1 + x)(适用于 x 接近 0)std::log1p(1e-5) ≈ 1e-5

<cmath> 三角与反三角函数表

函数功能示例
sin(x)计算弧度 x 的正弦值std::sin(pi / 2) == 1.0
cos(x)计算弧度 x 的余弦值std::cos(pi) == -1.0
tan(x)计算弧度 x 的正切值std::tan(0.0) == 0.0
asin(x)计算反正弦,x ∈ [-1,1],返回 [-π/2, π/2] 弧度std::asin(1.0) ≈ 1.5708
acos(x)计算反余弦,x ∈ [-1,1],返回 [0, π] 弧度std::acos(-1.0) ≈ 3.14159
atan(x)计算反正切,返回 (-π/2, π/2) 弧度std::atan(1.0) ≈ 0.7854
atan2(y, x)根据 (x, y) 符号计算完整象限辐角,返回 (-π, π]std::atan2(1.0, 1.0) ≈ 0.7854

<cmath> 双曲与反双曲函数表

函数功能示例
sinh(x)计算双曲正弦 (e^x - e^-x)/2std::sinh(0.0) == 0.0
cosh(x)计算双曲余弦 (e^x + e^-x)/2std::cosh(0.0) == 1.0
tanh(x)计算双曲正切 sinh(x)/cosh(x)std::tanh(1.0) ≈ 0.7616
asinh(x)计算反双曲正弦std::asinh(1.0) ≈ 0.8814
acosh(x)计算反双曲余弦(定义域 x ≥ 1)std::acosh(1.0) == 0.0
atanh(x)计算反双曲正切(定义域 -1 < x < 1)std::atanh(0.5) ≈ 0.5493

<cmath> 取整与浮点拆分函数表

函数功能示例
ceil(x)向上取整:返回不小于 x 的最小整数值std::ceil(2.3) == 3.0
floor(x)向下取整:返回不大于 x 的最大整数值std::floor(2.3) == 2.0
trunc(x)向零截断:直接舍去小数部分std::trunc(2.8) == 2.0
round(x)四舍五入(中间值 0.5 远离零舍入),返回浮点型std::round(2.5) == 3.0
lround(x)四舍五入并返回 long 整型std::lround(2.5) == 3L
llround(x)四舍五入并返回 long long 整型std::llround(2.5) == 3LL
nearbyint(x)按当前舍入模式取整(默认偶数舍入),不触发 FE_INEXACTstd::nearbyint(2.5) == 2.0
rint(x)按当前舍入模式取整(默认偶数舍入),可能置位 FE_INEXACTstd::rint(2.5) == 2.0
modf(x, &intpart)将 x 拆分为整数部分(写入 intpart)与小数部分(返回值)std::modf(2.3, &ip) -> 0.3, ip=2.0

<cmath> 浮点数分类与符号检查函数表

函数功能示例
isfinite(x)检查 x 是否为有限实数(非 ±Inf 且非 NaN)std::isfinite(3.0) == true
isinf(x)检查 x 是否为正无穷或负无穷std::isinf(inf) == true
isnan(x)检查 x 是否为非数字 NaNstd::isnan(qnan) == true
isnormal(x)检查 x 是否为正规非零浮点数(非零、非次正规、非 Inf/NaN)std::isnormal(1.0) == true
signbit(x)检查 IEEE 754 符号位是否为负(含 -0.0)std::signbit(-5.3) == true

实测 <cmath> 基本算术与指数对数、三角双曲、舍入拆分及浮点状态/域错误 NaN

含完整源码 · 156 行
展开查看收起
cpp
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <string>
#include <vector>

namespace lab {

struct Case {
    std::string name;
    std::string expected_json;
    std::string actual_json;
    bool passed;
};

std::string esc(const std::string& s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        switch (c) {
            case '\"': out += "\\\""; break;
            case '\\': out += "\\\\"; break;
            case '\b': out += "\\b"; break;
            case '\f': out += "\\f"; break;
            case '\n': out += "\\n"; break;
            case '\r': out += "\\r"; break;
            case '\t': out += "\\t"; break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof(buf), "\\u%04x", c);
                    out += buf;
                } else {
                    out += static_cast<char>(c);
                }
        }
    }
    out += "\"";
    return out;
}

std::string jbool(bool v) { return v ? "true" : "false"; }

bool near(double a, double b, double eps = 1e-6) {
    return std::fabs(a - b) <= eps;
}

void emit(const std::vector<Case>& cases) {
    std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
    for (std::size_t i = 0; i < cases.size(); ++i) {
        if (i) std::cout << ", ";
        std::cout << "{\"name\": " << esc(cases[i].name)
                  << ", \"expected\": " << cases[i].expected_json
                  << ", \"actual\": " << cases[i].actual_json
                  << ", \"passed\": " << jbool(cases[i].passed) << "}";
    }
    std::cout << "]}\n";
}

} // namespace lab

int main() {
    std::vector<lab::Case> cases;

    // Case 1: basic math + exp/log/power/root + long double suffix
    bool ok1 = (std::abs(-5) == 5)
        && lab::near(std::fabs(-5.5), 5.5)
        && lab::near(std::fmod(5.3, 2.0), 1.3)
        && lab::near(std::remainder(5.5, 2.0), -0.5)
        && lab::near(std::fmax(3.5, 4.2), 4.2)
        && lab::near(std::fmin(3.5, 4.2), 3.5)
        && lab::near(std::hypot(3.0, 4.0), 5.0)
        && lab::near(std::exp(1.0), 2.718281828)
        && lab::near(std::log(std::exp(1.0)), 1.0)
        && lab::near(std::log10(100.0), 2.0)
        && lab::near(std::pow(2, 3), 8.0)
        && lab::near(std::sqrt(16.0), 4.0)
        && lab::near(std::cbrt(27.0), 3.0)
        && lab::near(std::expm1(1.0), std::exp(1.0) - 1.0)
        && lab::near(std::log1p(1e-5), 9.99995e-6, 1e-9)
        && lab::near(static_cast<double>(std::sqrt(9.0L)), 3.0)
        && lab::near(static_cast<double>(sqrtl(9.0L)), 3.0);
    cases.push_back({
        "cmath_basic_and_exp_log",
        lab::jbool(true),
        lab::jbool(ok1),
        ok1
    });

    // Case 2: trigonometric and hyperbolic functions
    const double pi = std::acos(-1.0);
    bool ok2 = lab::near(std::sin(pi / 2.0), 1.0)
        && lab::near(std::cos(pi), -1.0)
        && lab::near(std::tan(0.0), 0.0)
        && lab::near(std::asin(1.0), pi / 2.0)
        && lab::near(std::acos(-1.0), pi)
        && lab::near(std::atan(1.0), pi / 4.0)
        && lab::near(std::atan2(1.0, 1.0), pi / 4.0)
        && lab::near(std::sinh(0.0), 0.0)
        && lab::near(std::cosh(0.0), 1.0)
        && lab::near(std::tanh(1.0), 0.761594156)
        && lab::near(std::asinh(1.0), 0.881373587)
        && lab::near(std::acosh(1.0), 0.0)
        && lab::near(std::atanh(0.5), 0.549306144);
    cases.push_back({
        "cmath_trig_and_hyperbolic",
        lab::jbool(true),
        lab::jbool(ok2),
        ok2
    });

    // Case 3: rounding and modf
    double intpart = 0.0;
    double fracpart = std::modf(2.3, &intpart);
    bool ok3 = lab::near(std::ceil(2.3), 3.0)
        && lab::near(std::floor(2.3), 2.0)
        && lab::near(std::trunc(2.8), 2.0)
        && lab::near(std::round(2.5), 3.0)
        && (std::lround(2.5) == 3L)
        && (std::llround(2.5) == 3LL)
        && lab::near(std::nearbyint(2.5), 2.0)
        && lab::near(std::rint(2.5), 2.0)
        && lab::near(intpart, 2.0)
        && lab::near(fracpart, 0.3);
    cases.push_back({
        "cmath_rounding_and_modf",
        lab::jbool(true),
        lab::jbool(ok3),
        ok3
    });

    // Case 4: floating-point classification and domain NaN (no C++ exception thrown)
    double pos_inf = std::numeric_limits<double>::infinity();
    double qnan = std::numeric_limits<double>::quiet_NaN();
    double neg_sqrt = std::sqrt(-1.0);
    bool ok4 = std::isfinite(3.0)
        && !std::isfinite(pos_inf)
        && std::isinf(pos_inf)
        && std::isnan(qnan)
        && std::isnan(neg_sqrt)
        && std::isnormal(1.0)
        && !std::isnormal(0.0)
        && std::signbit(-5.3)
        && !std::signbit(5.3);
    cases.push_back({
        "cmath_float_classify_and_domain",
        lab::jbool(true),
        lab::jbool(ok4),
        ok4
    });

    lab::emit(cases);
    return 0;
}
确认 abs/fabs/fmod/remainder(-0.5)/hypot/exp/log/pow/sqrt/cbrt/expm1/log1p/sqrtl、三角与双曲函数、ceil/floor/trunc/round/lround/llround/nearbyint(2)/rint(2)/modf 及 isfinite/isinf/isnan/isnormal/signbit 全部通过。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2307.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2337.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

不会抛出 C++ 异常。`<cmath>` 继承 C 数学库错误模型,域错误按 `math_errhandling` 设置 `errno`/`FE_INVALID` 并返回 `NaN`;调用后应通过 `std::isnan(res)` 或在调用前检查参数非负来防御。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习