所以在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'
").
使用-lm
while编译链接数学库.这取决于您的环境.
例如,如果您使用Windows,则不需要这样做,但它在基于UNIX的系统中.
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)
在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()
.
对于另一种方法,请注意所有标准库函数都使用浮点类型.您可以实现这样的整数类型函数:
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)
这有效地重复多次,但通过使用位表示减少了一点.对于低整数幂,这是非常有效的.