Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,因此它是on-topic,用于堆栈溢出。
                        
                        3年前关闭。
                                                                                            
                
        
请,有人可以帮助我如何在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;
}


编译:

gcc -Wall -o logprog logprog.c -lm


输出:

log(42.000000) = 5.392317

关于c - C语言的对数以2为底,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40900069/

10-16 04:37