Joh*_*itb 90
std::pow在<cmath>标头中有这些重载:
pow(float, float);
pow(float, int);
pow(double, double); // taken over from C
pow(double, int);
pow(long double, long double);
pow(long double, int);
Run Code Online (Sandbox Code Playgroud)
现在你不能这样做
pow(2, N)
Run Code Online (Sandbox Code Playgroud)
N是一个int,因为它不知道它应该采用float,double或long double版本,你会得到一个歧义错误.这三个都需要从int转换到浮点,这三个都是同样昂贵的!
因此,请务必键入第一个参数,以便它与这三个中的一个完美匹配.我经常使用float
pow(2.0, N)
Run Code Online (Sandbox Code Playgroud)
一些律师再次对我说话.我自己经常陷入这个陷阱,所以我要警告你.
小智 19
在C++中,"^"运算符是按位OR.它不适用于提升电力.x << n是二进制数的左移,与x乘以2 n次相同,只能在将2加到幂时使用.POW函数是一个通用的数学函数.
lea*_*der 11
虽然这pow( base, exp )是一个很好的建议,但要注意它通常在浮点运行.
这可能是你想要的也可能不是你想要的:在某些系统上,对于整数类型,累加器上的简单循环乘法会更快.
特别是对于方块,您可能只是将数字乘以自己,浮点或整数; 它并不是真正降低可读性(恕我直言),而是避免了函数调用的性能开销.
我没有足够的声誉来评论,但如果你喜欢使用QT,他们就有自己的版本.
#include <QtCore/qmath.h>
qPow(x, y); // returns x raised to the y power.
Run Code Online (Sandbox Code Playgroud)
或者如果你没有使用QT,cmath基本上都是一样的.
#include <cmath>
double x = 5, y = 7; //As an example, 5 ^ 7 = 78125
pow(x, y); //Should return this: 78125
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
#include <conio.h>
using namespace std;
double raiseToPow(double ,int) //raiseToPow variable of type double which takes arguments (double, int)
void main()
{
double x; //initializing the variable x and i
int i;
cout<<"please enter the number";
cin>>x;
cout<<"plese enter the integer power that you want this number raised to";
cin>>i;
cout<<x<<"raise to power"<<i<<"is equal to"<<raiseToPow(x,i);
}
Run Code Online (Sandbox Code Playgroud)
//函数raiseToPower的定义
double raiseToPow(double x, int power)
{
double result;
int i;
result =1.0;
for (i=1, i<=power;i++)
{
result = result*x;
}
return(result);
}
Run Code Online (Sandbox Code Playgroud)
首先添加#include <cmath>,然后您可以在代码中使用powmethode 例如:
pow(3.5, 3);
Run Code Online (Sandbox Code Playgroud)
其中3.5是基数,3是指数
pow(2.0,1.0)
pow(2.0,2.0)
pow(2.0,3.0)
Run Code Online (Sandbox Code Playgroud)
您的原始问题标题具有误导性。要只是平方,请使用2*2.
许多答案已经提出了建议pow()或类似的替代方案或它们自己的实现。然而,给出的例子(2^1,2^2并2^3在你的问题),我猜你是否只需要筹集2到的整数次幂。如果是这样的话,我建议你使用1 << n的2^n。
如果只想处理base_2,那么我建议使用左移运算符<<而不是数学库。
示例代码:
int exp = 16;
for(int base_2 = 1; base_2 < (1 << exp); (base_2 <<= 1)){
std::cout << base_2 << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
样本输出:
1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768
Run Code Online (Sandbox Code Playgroud)