C++ x 的对数基数 n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18874255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:16:52  来源:igfitidea点击:

Log base n of x

c++mathlogarithm

提问by Amirhossein Mahdinejad

I have a little problem. Who knows how we can calculate the log base n with Shift_L or Shift_R?

我有一个小问题。谁知道我们如何使用 Shift_L 或 Shift_R 计算对数基数 n?

for example: for n=2 we had this solution:

例如:对于 n=2 我们有这个解决方案:

int log(int n){
int res = 0;
while((n>>=1))
    res++;
return res;
}

回答by Carsten

You don't seem to want the logarithm for a base b, but the largest integer nso that n <= log_b(x). If that's the case, the following function should serve your needs:

您似乎不需要 base 的对数b,而是最大的整数,n以便n <= log_b(x). 如果是这种情况,以下功能应该可以满足您的需求:

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

回答by Teh Suu

well this is rather a math problem instead of an actuall programming problem, if i understand your problem correctly:

好吧,如果我正确理解您的问题,这更像是一个数学问题而不是实际的编程问题:

log_2 (x) = log_a (x) / log_a (2)where a can be any base.

log_2 (x) = log_a (x) / log_a (2)其中 a 可以是任何基数。

Therefore you could use the math.h's function log(double)

因此你可以使用math.h's 函数log(double)

double res = log(x)/log(2);

double res = log(x)/log(2);