How to calculate the exponent/power value (how much of the power) i.e. 'n' in c++? [closed]

StackOverflow https://stackoverflow.com/questions/23444626

  •  14-07-2023
  •  | 
  •  

How can we calculate the value/degree of power exponent of a certain number?

I mean if it's like a^n = b, then how can we calculate n?

For example assume that a = 2 and b = 8, then how can we calculate that n = 3? Is there any special function?

有帮助吗?

解决方案 3

Well, you can use the same logarithmic functions here too. Include cmath.

In-code

.
. 
cout << log(8) / log(3) << endl;
.
.

Output

   .
   .
   .
...3...
   .
   .
   .

其他提示

Use std::log. Example from the reference page:

#include <cmath>
#include <iostream>

int main()
{
    double base = 2.0;
    double arg  = 8.0;
    double result = std::log(arg) / std::log(base);

    std::cout << result << '\n'; // prints 3
}

More to learn at wikipedia.

What you are looking for is the logarithm of b to the base a (at least we call it that in german).

C++ example:

#include <cmath>       /* log */

int main ()
{
  int a = 2;
  int b = 8;
  float n = log(b) / log(a); // 3
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top