C语言中的对数基2

C语言中的对数基2,c,logarithm,C,Logarithm,请问,有人能帮我计算C中的简单log2吗?我尝试使用此代码,但不起作用: printf( "log( %f ) = %f\n", x, log2(x) ); 您还可以创建一个助手函数,该函数可以转换为您想要的任何日志库: 大概是这样的: #include <stdio.h> #include <stdlib.h> #include <math.h> double my_log(double x, int base) { return log(x

请问,有人能帮我计算C中的简单log2吗?我尝试使用此代码,但不起作用:

printf( "log( %f ) = %f\n", x, log2(x) );

您还可以创建一个助手函数,该函数可以转换为您想要的任何日志库:

大概是这样的:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double 
my_log(double x, int base) { 
    return log(x) / log(base); 
} 

int 
main(void) {
    double x = 42.0;

    printf("log(%f) = %f\n", x, my_log(x, 2));

    return 0;
}
输出:

log(42.000000) = 5.392317

Explain不起作用可能与的重复,那么为什么OP的代码不起作用?@Rightleg可能丢失,这意味着返回值错误地默认为int。他可能还需要使用-lm进行编译,具体取决于他使用的gcc版本。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double 
my_log(double x, int base) { 
    return log(x) / log(base); 
} 

int 
main(void) {
    double x = 42.0;

    printf("log(%f) = %f\n", x, my_log(x, 2));

    return 0;
}
gcc -Wall -o logprog logprog.c -lm
log(42.000000) = 5.392317