c ++试图找出对数计算

c++ trying to figure out logarithms calculations

因此,如果我正确理解 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”,但我不确定如何真正使用对数库..

一道对数题分为三部分。基础、论点(也称为权力)和答案。您正在尝试计算 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;

大多数情况下,对数的实现是一个以 e 为底的近似对数的泰勒函数。要获得任何其他底数的对数,您可以这样做:

#include <cmath>
double y = std::log(x)/std::log(base);

描述:

  • std::log() 以 e 为底的自然对数。
  • y = 结果
  • base = 对数的底数。喜欢 2 或 10。

供您参考:

这里有一个不使用 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;
}