Processing math: 100%

PHP – 如何使用 bcmod() 函数获取任意精度数的模?


在 PHP 中,**bcmod()** 数学函数用于计算任意精度数的模。**bcmod()** 函数将任意精度数作为字符串,并将结果作为数字的模,并将结果缩放至指定的精度。或者,我们可以说它获取 **string_num1** 除以 **string_num2** 后的余数。除非 **string_num2** 为 0,否则结果与 **string_num1** 具有相同的符号。

语法

bcmod(string_$num1, string_$num2, [, int $scale=0])

或者,

bcmod(string $dividend, string $divisor[, int $scale=0])

注意− 以上语法将获取 **stringnum1string_num2** 的余数。除非 **string_num2** 为 0,否则结果与 **string_num1** 具有相同的符号。

参数

**bcmod()** 函数接受两个不同的参数,**dividendmodulus**。

  • **dividendmodulus 除的被除数,它是字符串类型参数。

  • **$modulus−** 它是字符串类型参数,用于表示模数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

**bcmod()** 函数返回被除数除以模数的余数。如果模数为 0,则函数返回 null。

示例 1 - 不使用 scale 参数的 bcmod() PHP 函数。

<?php
   // input numbers with arbitrary precision
   $dividend = "25.666";
   $modulus = "7";

   // calculates the modulus
   $result = bcmod($dividend, $modulus);
   echo "Output without using scale value: ", $result;
?>

输出

Output without using scale value: 4

示例 2 - 使用 scale 参数的 bcmod() PHP 函数

现在,我们将使用 scale 值为 4 的相同输入值并检查输出。

<?php
   // input numbers with arbitrary precision
   $dividend = "25.666";
   $modulus = "7";

   //using scale value 4
   $scaleVal =4;

   // calculates the modulus
   $result = bcmod($dividend, $modulus, $scaleVal);
   echo "Output with scale value: ", $result;
?>

输出

Output with scale value: 4.6660

示例 3

<?php
   bcscale(1);

   // 0.5 as of PHP 7.2.0; 0 previously
   echo bcmod('5.7', '1.3');
?>

输出

0.5

注意− scale 参数从 PHP 7.2.0 版本开始添加。

更新于:2021年8月21日

219 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始
广告