编写程序以在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 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志