如何在 C++ 中计算对数基数 2?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14872078/
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
How can I calculate log base 2 in c++?
提问by user2036891
Here is my code.
这是我的代码。
#include <iostream>
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include <cmath>
#include <functional>
using namespace std;
void main()
{
cout<<log2(3.0)<<endl;
}
But above code gives error. Error code is : error C3861: 'log2': identifier not found. How can i calculate log2 using c++?
但是上面的代码给出了错误。错误代码是:错误 C3861:'log2':未找到标识符。如何使用 C++ 计算 log2?
回答by Hayri U?ur Koltuk
for example for log 3 in base 2
例如对于基数 2 中的日志 3
log (3) / log(2)
will do it.
会做的。
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << log(3.0) / log(2.0) << endl;
}
回答by quetzalcoatl
Using highschool mathematics:
使用高中数学:
log_y(x) = ln(x)/ln(y)
But I agree, that's a little strange that there's no such utility function out there. That's probably due to the almost-direct mapping of those functions to FPU..
但我同意,这有点奇怪,那里没有这样的实用功能。这可能是由于这些功能几乎直接映射到 FPU ..
However do not worry about using this 'expanded' way. The mathematics will not change. The formula will be valid for at least next few lifetimes.
但是,不要担心使用这种“扩展”方式。数学不会改变。该公式至少在接下来的几个生命周期中都有效。
回答by banarun
The following code works with gcc compiler
以下代码适用于 gcc 编译器
#include <iostream>
#include<stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cmath>
#include <functional>
using namespace std;
main()
{
cout<<log2(3.0)<<endl;
}
回答by user1833028
This should be a general function for finding the log with a base of any given number
这应该是一个通用函数,用于查找以任何给定数字为基数的日志
double log_base_n(double y, double base){
return log(y)/log(base);
}
so:
所以:
cout<<log_base_n(3.0,2.0);
ought to do the trick.
应该做的伎俩。
回答by Abhishek Thakur
use log(3.0)/log(2.0)
. log2
is not included in C90.
使用log(3.0)/log(2.0)
. log2
不包括在 C90 中。
double log_2( double n )
{
return log(n) / log(2);
}