【C++库函数】C++求对数的方法

对数换底公式

C++17以下不能直接求log2(),需要用换底公式
$ \log_b a = \frac{\ln a}{\ln b}$
C++17及以上可以直接用log2()函数
image

完整实例

#include <iostream>
#include <cmath>

int main() {
    double x = 100.0;

    // 自然对数
    std::cout << "ln(100) = " << log(x) << std::endl;      // 输出 ~4.60517

    // 以10为底
    std::cout << "log10(100) = " << log10(x) << std::endl; // 输出 2

    // 以2为底(C++17+)
    #if __cplusplus >= 201703L
    std::cout << "log2(64) = " << log2(64.0) << std::endl; // 输出 6
    #endif

    // 任意底数(例如 log₃ 81)
    std::cout << "log3(81) = " << log(81) / log(3) << std::endl; // 输出 4

    return 0;
}

image

posted @ 2025-03-04 21:23  Tshaxz  阅读(654)  评论(0)    收藏  举报
Language: HTML