所以在python中,我所要做的就是
print(3**4)
这给了我81
我如何在C中执行此操作?我搜索了一下并说出exp()
函数,但不知道如何使用它,提前谢谢
答案 0 :(得分:59)
您需要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);
这里x是基数,y是指数。结果是x^y
。
用法
pow(2,4);
result is 2^4 = 16. //this is math notation only
// In c ^ is a bitwise operator
并确保包含math.h
以避免警告(“incompatible implicit declaration of built in function 'pow'
”)。
编译时使用-lm
链接数学库。这取决于您的环境
例如,如果您使用Windows,则不需要这样做,但它在基于UNIX的系统中。
答案 1 :(得分:9)
#include <math.h>
printf ("%d", (int) pow (3, 4));
答案 2 :(得分:8)
在C语言中没有运算符用于此类用法,而是一系列函数:
double pow (double base , double exponent);
float powf (float base , float exponent);
long double powl (long double base, long double exponent);
请注意,后两者仅是自C99以来标准C的一部分。
如果您收到如下警告:
“内置函数'pow'的不兼容隐式声明”
那是因为你忘记了#include <math.h>
。
答案 3 :(得分:8)
您可以使用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);
}
答案 4 :(得分: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;
}
这有效地重复多次,但通过使用位表示减少了一点。对于低整数幂,这非常有效。
答案 5 :(得分:4)
只需使用pow(a,b)
,这在python中完全是3**4
答案 6 :(得分:3)
实际上在C中,您没有电源操作员。您需要手动运行循环才能获得结果。即使是exp函数也只是以这种方式运行。但是,如果您需要使用该功能,请包含以下标题
#include <math.h>
然后你可以使用pow()。