當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。