C++程序计算数字的幂
数字的幂可以计算为 x^y,其中 x 是数字,y 是其幂。
例如。
Let’s say, x = 2 and y = 10 x^y =1024 Here, x^y is 2^10
数字的幂可以使用递归和非递归程序来计算。以下是每种方法的示例。
使用非递归程序计算数字的幂
使用非递归程序查找数字的幂的程序如下所示:
示例
#include<iostream>
using namespace std;
int power(int x, int y) {
int i,power=1;
if(y == 0)
return 1;
for(i=1;i<=y;i++)
power=power*x;
return power;
}
int main() {
int x = 3;
int y = 4;
cout<<"x = "<<x<<endl;;
cout<<"y = "<<y<<endl;
cout<<"x^y = "<<power(x,y);
return 0;
}x = 3 y = 4 x^y = 81
在上述程序中,函数 power() 用于计算数字的幂。它是一个非递归函数。在函数中,使用了一个 for 循环,该循环从 1 运行到 y。对于循环的每次迭代,x 都乘以 power。
因此,x 自身乘以 y 次,结果存储在 power 中。这导致 x^y 存储在 power 中。然后将 power 返回到 main() 函数。
以下代码片段演示了这一点:
int power(int x, int y) {
int i, power = 1;
if(y==0)
return 1;
for(i=1;i<=y;i++)
power = power*x;
return power;
}在 main() 中,显示 x、y 和 x^y 的值。这在下面给出的代码片段中显示:
cout<<"x = "<<x<<endl;; cout<<"y = "<<y<<endl; cout<<"x^y = "<<power(x,y);
使用递归程序计算数字的幂
使用递归程序查找数字的幂的程序如下所示。
示例
#include<iostream>
using namespace std;
int power(int x, int y) {
if (y == 0)
return 1;
else if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
else
return x*power(x, y/2)*power(x, y/2);
}
int main() {
int x = 3;
int y = 4;
cout<<"x = "<<x<<endl;;
cout<<"y = "<<y<<endl;
cout<<"x^y = "<<power(x,y);
return 0;
}输出
x = 3 y = 4 x^y = 81
在上述程序中,power() 是一个递归函数。如果 y 的值为 0,则返回 1。如果 y 是偶数,则它使用 x 和 y/2 的值递归调用自身,并返回 power(x, y/2)*power(x, y/2)。如果 y 是奇数,则它使用 x 和 y/2 的值递归调用自身,并返回 x*power(x, y/2)*power(x, y/2)。这由以下代码片段演示。
int power(int x, int y) {
if (y == 0)
return 1;
else if (y%2 == 0)
return power(x, y/2)*power(x, y/2);
else
return x*power(x, y/2)*power(x, y/2);
}在 main() 中,显示 x、y 和 x^y 的值。这在下面给出的代码片段中显示。
cout<<"x = "<<x<<endl;; cout<<"y = "<<y<<endl; cout<<"x^y = "<<power(x,y);
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP