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


C++ sqrt()用法及代碼示例

C++ sqrt() 函數

sqrt() 函數是 cmath 頭文件(早期版本為<math.h>)的庫函數,用於求給定數字的平方根,它接受一個數字並返回平方根。

注意:如果我們提供負值,sqrt() 函數將返回域錯誤。 (-nan)。

sqrt() 函數的語法:

    sqrt(x);

參數: x– 要計算其平方根的數字。

返回值: double– 它返回雙精度值,即給定數字的平方根x

例:

    Input:
    int x = 2;

    Function call:
    sqrt(x);

    Output:
    1.41421

C++代碼演示sqrt()函數的例子

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

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

// main code section
int main()
{
    float x;
    
    //input the value
    cout<<"Enter a number:";
    cin>>x;

    // calculate the square root
    float result = sqrt(x);
    cout<<"square root of "<<x<<" is = "<<result;
    cout<<endl;
    
    return 0;
}

輸出

First run:
Enter a number:4
square root of 4 is = 2 

Second run:
Enter a number:10.234 
square root of 10.234 is = 3.19906

Third run:
Enter a number:0
square root of 0 is = 0

Fourth run:
Enter a number:-10
square root of -10 is = -nan 


相關用法


注:本文由純淨天空篩選整理自 sqrt() function with example in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。