编写程序以在C ++中计算pow(x,n)
在这个问题上,我们给了两个整数x和n。我们的任务是编写一个程序来计算pow(x,n)。
让我们举个例子来了解这个问题,
输入值
x = 5 , n = 3
输出结果
125
程序来计算pow(x,n),
示例
#include <iostream>
using namespace std;
float myPow(float x, int y) {
if(y == 0)
return 1;
float temp = myPow(x, y / 2);
if (y % 2 == 0)
return temp*temp;
else {
if(y > 0)
return x*temp*temp;
else
return (temp*temp)/x;
}
}
int main() {
float x = 5;
int n = 7;
cout<<x<<" raised to the power "<<n<<" is "<<myPow(x, n);
return 0;
}输出结果
5 raised to the power 7 is 78125
该程序显示了一种有效的方法,将幂分为一半,然后将两个部分相乘,然后考虑否定情况。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短