c ++试图找出对数计算
Posted
技术标签:
【中文标题】c ++试图找出对数计算【英文标题】:c++ trying to figure out logarithms calculations 【发布时间】:2015-10-15 23:51:20 【问题描述】:所以,如果我正确理解 c++ 和对数。像这样的东西应该给我我正在寻找的基地?
我遇到了一些问题,但认为这种方式是一个正确的开始。
#include <iostream>
using namespace std;
int main(void)
int x = 2;
int y = 64;
int value = log x (y);
cout << value << endl;
return 0;
这应该显示“6”,但我不确定如何真正使用对数库..
【问题讨论】:
我投票结束这个问题,因为它不是关于编程的。 对不起,这是一个编程问题 赞成,因为我认为这是不公平的反对票。 【参考方案1】:对数问题包含三个部分。基础、论据(也称为幂)和答案。您试图找出 2(底数)必须乘以得到 64(答案)的次数。
所以不要处理权力和猜测。让我们计算一下我们将答案 64 除以基数的次数,直到得到 1。
64 / 2 = 32
32 / 2 = 16
16 / 2 = 8
8 / 2 = 4
4 / 2 = 2
2 / 2 = 1
这里我们数了 6 行,所以您将答案 64 除以基数 2,共 6 次。这与说你将 2 的 6 次方加到 64 是一样的。
嗯,要让它工作,你需要 math.h 库。如果您想在没有它的情况下执行此操作。你可以做一个循环,不断除以用户给出的基数。
int base = 0;
int answer = 0;
int exponent = 0;
cout << "Please type in your base";
cin >> base;
cout << "Please type in your answer";
cin >> answer;
while (answer != 1)
answer /= base;
exponent++
cout << "The exponent is " << exponent;
【讨论】:
我也将注销作为标签。也许用对数代替? 对不起,我忘了包括指数。这就是我们想要返回的。 谢谢塔斯!我还在学习。堆栈溢出太棒了!我希望我能回馈更多的知识。【参考方案2】:对数的实现大多数时候是一个以 e 为底的近似对数的 tayler 函数。要获得任何其他基数的对数,您可以执行以下操作:
#include <cmath>
double y = std::log(x)/std::log(base);
说明:
std::log() 以 e 为底的自然对数。 y = 结果 base = 对数的底。比如 2 个或 10 个。供您参考:
http://en.cppreference.com/w/cpp/numeric/math/log http://en.cppreference.com/w/c/numeric/math/log https://en.wikipedia.org/wiki/Logarithm https://en.wikipedia.org/wiki/Logarithm#Change_of_base https://en.wikipedia.org/wiki/Taylor_series https://en.wikipedia.org/wiki/Taylor_series#Examples【讨论】:
【参考方案3】:这是一个更好的实现,不使用 math.h 库。我可能有一些多余的代码,因为我用 C++ 编写已经有一年了。 (让我感到羞耻)谢谢你的问题,它让我想重新学习我的 C++!
#include <iostream>
#include <iomanip>
using namespace std;
int main()
float base = 0;
float answer = 0;
int exponent = 0;
cout.precision(4);
cout << "Please type in your base \n";
cin >> base;
cout << "Please type in your answer\n";
cin >> answer;
cout << fixed;
while (answer > base)
answer /= base;
exponent++;
cout << "The exponent is: " << exponent << endl;
cout << "The Remainder is: " << fixed << answer << endl;
return 0;
【讨论】:
以上是关于c ++试图找出对数计算的主要内容,如果未能解决你的问题,请参考以下文章