对于C的力量?
所以在python中,我所要做的就是
print(3**4)
这让我81
我怎么用C做这个? 我搜索了一下并说了exp()
函数,但不知道如何使用它,提前谢谢
你需要pow();
math.h
头文件中的函数。
句法
#include 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的系统中。
#include printf ("%d", (int) pow (3, 4));
在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
。
你可以使用#include
pow(base, power)
或创建自己的:
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); }
对于另一种方法,请注意所有标准库函数都使用浮点类型。 你可以实现这样的整数类型函数:
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; }
这有效地重复多次,但通过使用位表示减少了一点。 对于低整数功率,这是非常有效的。
只需使用pow(a,b)
,这在python中正好是3**4
实际上在C中,你没有电力操作员。 您需要手动运行循环才能获得结果。 即使是exp函数也只是以这种方式运行。 但是,如果您需要使用该function,请包含以下标题
#include
然后你可以使用pow()。