当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ pow()用法及代码示例


C++ pow() 函数

pow() 函数是 cmath 头文件(早期版本中为<math.h>)的库函数,用于求乘方,它接受两个参数并返回第一个参数的第二个参数的幂。

pow() 函数的语法:

    pow(x, y);

参数: x, y– 是要计算的数字x^y

返回值: double– 它返回计算结果的双精度值x的力量y

例:

    Input:
    float x = 2;
    float y = 3;

    Function call:
    pow(x,y);

    Output:
    8

C++代码演示pow()函数的例子

// C++ code to demonstrate the example of 
// pow() function

#include <iostream>
#include <cmath>
using namespace std;

// main code section
int main()
{
    float x;
    float y;
    
    //input the values
    cout<<"Enter the value of x:";
    cin>>x;
    cout<<"Enter the value of y:";
    cin>>y;
    
    // calculate the power
    float result = pow(x,y);
    cout<<x<<" to the power of "<<y<<" is = "<<result;
    cout<<endl;
    
    return 0;
}

输出

First run:
Enter the value of x:10 
Enter the value of y:5
10 to the power of 5 is = 100000

Second run:
Enter the value of x:10.23
Enter the value of y:1.5
10.23 to the power of 1.5 is = 32.72

Third run:
Enter the value of x:10 
Enter the value of y:0
10 to the power of 0 is = 1 

Fourth run:
Enter the value of x:0
Enter the value of y:1.5
0 to the power of 1.5 is = 0


相关用法


注:本文由纯净天空筛选整理自 pow() function with example in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。