English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

使用C ++编写电源(电源)功能

幂函数用于在给定两个数字(基数和指数)的情况下查找幂。结果是提高指数幂的基础。

一个证明这一点的例子如下-

Base = 2
Exponent = 5
2^5 = 32
Hence, 2 raised to the power 5 is 32.

演示C ++幂函数的程序如下所示-

示例

#include
using namespace std;
int main(){
   int x, y, ans = 1;
   cout << "Enter the base value: \n";
   cin >> x;
   cout << "Enter the exponent value: \n";
   cin >> y;
   for(int i=0; i<y; i++)
   ans *= x;
   cout << x <<" raised to the power "<< y <<" is "<&;lt;ans;
   return 0;
}

示例

上面程序的输出如下-

Enter the base value: 3
Enter the exponent value: 4
3 raised to the power 4 is 81

现在让我们了解上面的程序。

基数和指数的值是从用户那里获得的。显示此的代码段如下-

cout << "Enter the base value: \n";
cin >> x;
cout << "Enter the exponent value: \n";
cin >> y;

幂是使用for循环计算的,该循环一直运行到指数值。在每遍中,基值乘以ans。for循环完成后,幂的最终值存储在变量ans中。显示此的代码段如下-

for(int i=0; i<y; i++)
ans *= x;

最后,显示幂值。显示此的代码段如下-

cout << x <<" raised to the power "<< y <<" is "<<ans;