什么是C ++函数来提高数量的权力?

我如何提高一个数字的权力?

2^1 2^2 2^3 

等等…

pow()在cmath库中。 更多信息在这里 。 不要忘了在顶部有#include。

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); 

现在你不能这样做

 pow(2, N) 

N是一个int,因为它不知道应该使用哪一个float,double或long double版本,并且会得到一个模糊性错误。 所有这三个都需要一个从int到浮点的转换,并且这三个都是同样昂贵的!

因此,请确保input第一个参数,以便与其中的三个完全匹配。 我通常使用double

 pow(2.0, N) 

一些律师又从我身上扯下了。 我经常陷入这个陷阱,所以我要警告你。

使用pow(x,y)函数: 见这里

只要包括math.h,你就全部设置好了。

你应该能够在math中使用正常的C方法。

#include <cmath>

pow(2,3)

如果你的系统是unix系统的话,

那是你在问什么?

Sujal

虽然pow( base, exp )是一个很好的build议,但请注意,它通常以浮点运算。

这可能是也可能不是你想要的:在一些系统上,一个累加器上的简单循环乘以整数types将会更快。

对于正方形,你可能只需要将数字自己乘以浮点数或整数; 这不是真正的可读性下降(恕我直言),你可以避免函数调用的性能开销。

在C ++中,“^”运算符是一个按位或。 它不适合提高权力。 x << n是二进制数的左移,它与乘以x的次数相同,只能在提高2次幂时使用。 POW函数是一个通用的math函数。

我没有足够的声望发表评论,但如果你喜欢与QT合作,他们有自己的版本。

  #include <QtCore/qmath.h> qPow(x, y); // returns x raised to the y power. 

或者如果你不使用QT,cmath基本上是一样的东西。

  #include <cmath> double x = 5, y = 7; //As an example, 5 ^ 7 = 78125 pow(x, y); //Should return this: 78125 
 #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); } 

//定义函数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); } 

<math.h>是pow或powf

在Visual Basic或Python中没有特殊的中缀运算符

 pow(2.0,1.0) pow(2.0,2.0) pow(2.0,3.0) 

你原来的问题题目是误导性的。 为了方便,使用2*2

 int power (int i, int ow) // works only for ow >= 1 { // but does not require <cmath> library!=) if (ow > 1) { i = i * power (i, ow - 1); } return i; } cout << power(6,7); //you can enter variables here 

请注意pow(x,y)的使用效率低于x x x y次,如下所示,并在这里回答https://stackoverflow.com/a/2940800/319728

所以,如果你要提高效率,请使用x x x。

我正在使用库cmathmath.h以便使用pow()库函数来处理权力

 #include<iostream> #include<cmath> int main() { double number,power, result; cout<<"\nEnter the number to raise to power: "; cin>>number; cout<<"\nEnter the power to raise to: "; cin>>power; result = pow(number,power); cout<<"\n"<< number <<"^"<< power<<" = "<< result; return 0; }