PHP将整数数字转换为罗马数字实例分享分享!

方法一:自定义函数

我们可以自己手动编写一个函数来实现此功能,这个函数可以将数字作为第一个参数,将其转换为罗马并返回。

注:大多数算法只能在1-4999的范围内工作,如果使用特大数,脚本将失败。

实现代码:

  <?php    header("content-type:text/html;charset=utf-8");    //将数字转换为罗马表示形式    function numberToRoman($num)     {      // Be sure to convert the given parameter into an integer     $n = intval($num);     $result = '';           // Declare a lookup array that we will use to traverse the number:      $lookup = array(      'M' => 1000, 'CM' => 900, 'D' => 500, 'CD' => 400,       'C' => 100, 'XC' => 90, 'L' => 50, 'XL' => 40,       'X' => 10, 'IX' => 9, 'V' => 5, 'IV' => 4, 'I' => 1     );           foreach ($lookup as $roman => $value)      {      // Look for number of matches      $matches = intval($n / $value);            // Concatenate characters      $result .= str_repeat($roman, $matches);            // Substract that from the number       $n = $n % $value;      }      return $result;     }     echo '整数数字转换为罗马数字:<br><br>';    // VIII    echo '数字8:'.numberToRoman(8).'<br>';    // CXXIII    echo '数字123:'.numberToRoman(123).'<br>';    // MMCCCLV    echo '数字2355:'.numberToRoman(2355).'<br>';    // MMMMCMXCIX    echo '数字4999:'.numberToRoman(4999).'<br>';    ?>

输出:

PHP将整数数字转换为罗马数字实例分享

方法二:使用Romans库

Romans库是一个非常简单的PHP罗马数字库,允许您将整数转换为其罗马表示,反之亦然。

注:如果没有该库,请先需要安装;安装好Romans库后,就能够使用其命名空间并使用可帮助转换数字的函数。

Romans库包含一对简单的过滤器,用于将具有罗马数字的字符串转换为表示输入为十进制的int,将十进制int转换为具有罗马数字作为结果的字符串。

1、整数转换为罗马数字

要将整数转换为罗马表示,需要使用IntToRoman类,创建一个实例并从中调用filter方法。此方法将数字作为第一个参数,并返回带有罗马数字的字符串:

  <?php    use RomansFilterIntToRoman;         $filter = new IntToRoman();    $result = $filter->filter(1999);    echo $result;    ?>

输出:

MCMXCIX

2、罗马数字转换为整数

要将罗马数字转换为整数表示,需要使用RomanToInt类,创建一个实例并从中调用filter方法。此方法将使用罗马数字的字符串作为第一个参数,并返回一个带数值的整数:

  <?php    use RomansFilterRomanToInt;         $filter = new RomanToInt();    $result = $filter->filter('MCMXCIX');    echo $result;    ?>

输出:

1999

—-想了解PHP将整数数字转换为罗马数字实例分享分享!且更多的php教程关注<计算机技术网(www.ctvol.com)!!>

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/phpttorial/481353.html

(0)
上一篇 2020年11月10日
下一篇 2020年11月10日

精彩推荐