为了C的力量?

sam*_*mir 34 c math

所以在python中,我所要做的就是

print(3**4) 
Run Code Online (Sandbox Code Playgroud)

这让我81

我怎么用C做这个?我搜索了一下并说出了这个exp()功能,但不知道如何使用它,在此先感谢

Gan*_*har 64

你需要头部的pow();功能math.h.
句法

#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
Run Code Online (Sandbox Code Playgroud)

这里x是基数,y是指数.结果是x^y.

用法

pow(2,4);  

result is 2^4 = 16. //this is math notation only   
// In c ^ is a bitwise operator
Run Code Online (Sandbox Code Playgroud)

并确保包含math.h 以避免警告(" incompatible implicit declaration of built in function 'pow'").

使用-lmwhile编译链接数学库.这取决于您的环境.
例如,如果您使用Windows,则不需要这样做,但它在基于UNIX的系统中.

  • 几个次要点-首先,y是指数,不是指数,_result_是指数(它是形容词,而不是名词)。其次,在C语言中没有关于与`-lm`链接的事情,这是实现的事情,并且由于OP没有声明其环境,因此假设这样做是不明智的。 (2认同)
  • @paxdiablo函数是指数(形容词),指数有变化,结果是指数的基数幂(名词). (2认同)

ver*_*ose 10

#include <math.h>


printf ("%d", (int) pow (3, 4));
Run Code Online (Sandbox Code Playgroud)


小智 9

您可以使用pow(base, exponent)#include <math.h>

或创建自己的:

int myPow(int x,int n)
{
    int i; /* Variable used in loop counter */
    int number = 1;

    for (i = 0; i < n; ++i)
        number *= x;

    return(number);
}
Run Code Online (Sandbox Code Playgroud)

  • 第二个参数称为指数.结果被称为权力. (3认同)

Yu *_*Hao 8

在C语言中没有运算符用于此类用法,而是一系列函数:

double pow (double base , double exponent);
float powf (float base  , float exponent);
long double powl (long double base, long double exponent);
Run Code Online (Sandbox Code Playgroud)

请注意,后两者仅是C99以来标准C的一部分.

如果您收到如下警告:

"内置函数'pow'的不兼容隐式声明"

那是因为你忘记了#include <math.h>.


小智 5

实际上,在 C 语言中没有幂运算符。您将需要手动运行循环才能获得结果。甚至 exp 函数也只是以这种方式运行。但如果您需要使用该功能,请包含以下标头

#include <math.h>
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用pow().

  • @samir 它与许多语言中的 *import* 并不完全相同。C `#include` 只是将包含文件的内容插入到编译中,您可以通过自己编写正确的声明来达到相同的效果。在其他语言中,*import* 在更抽象的级别上工作。但目的是一样的。 (4认同)

Kei*_*ith 5

对于另一种方法,请注意所有标准库函数都使用浮点类型.您可以实现这样的整数类型函数:

unsigned power(unsigned base, unsigned degree)
{
    unsigned result = 1;
    unsigned term = base;
    while (degree)
    {
        if (degree & 1)
            result *= term;
        term *= term;
        degree = degree >> 1;
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

这有效地重复多次,但通过使用位表示减少了一点.对于低整数幂,这是非常有效的.