PHP – 如何使用 bcsqrt() 函数求任意精度数的平方根?

phpserver side programmingprogramming更新于 2025/7/22 14:37:17

在 PHP 中,bcsqrt() 函数用于求任意精度数的平方根。该函数接受任意精度数作为字符串,并将结果缩放到指定精度后,返回该数的平方根。

语法

string bcsqrt($num_string, $scale)

参数

bcsqrt() 函数接受两个不同的参数:$num_string 和 $scale。

  • $num_string − 表示要求其平方根的数。它是一个字符串类型参数。

  • $scale − 表示输出中小数点后的位数。

返回值

bcsqrt() 函数以字符串形式返回数字的平方根。

示例 1

<?php
   // 输入任意精度的数字
   $num_string = "22";

   // 下面的 bcsqrt 函数计算平方根
   $result= bcsqrt($num_string);
   echo "Output without scale value: ", $result;
?>

输出

Output without scale value: 4

示例 2

<?php
   // 输入任意精度的数字
   $num_string = "22";

   //比例值为 3
   $scale="3";

   // 下面的 bcsqrt 函数计算平方根
   $result= bcsqrt($num_string, $scale);
   echo "Output with scale value: ", $result;
?>

输出

Output with scale value: 4.690

相关文章