欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php实现阿拉伯数字和罗马数字相互转换的方法

程序员文章站 2022-06-18 16:23:37
本文实例讲述了php实现阿拉伯数字和罗马数字相互转换的方法。分享给大家供大家参考。具体如下:

本文实例讲述了php实现阿拉伯数字和罗马数字相互转换的方法。分享给大家供大家参考。具体如下:

<?php
// function that calculates the roman string to the given number:
function dec2roman($f)
{
 // return false if either $f is not a real number, 
 //$f is bigger than 3999 or $f is lower or equal to 0:  
  if(!is_numeric($f) || $f > 3999 || $f <= 0) return false;
 // define the roman figures:
  $roman = array(
  'm' => 1000,
  'd' => 500,
  'c' => 100,
  'l' => 50,
  'x' => 10,
  'v' => 5,
  'i' => 1
  );
 // calculate the needed roman figures:
  foreach($roman as $k => $v)
  if(($amount[$k] = floor($f / $v)) > 0)
  $f -= $amount[$k] * $v;
 // build the string:
  $return = '';
  foreach($amount as $k => $v)
  {
   $return .= $v <= 3 ? str_repeat($k, $v) : $k . $old_k;
   $old_k = $k;  
  }
 // replace some spacial cases and return the string:
  return str_replace(array('viv','lxl','dcd'),array('ix','xc','cm'),$return);
}
// echo dec2romen(1981);
// function to get the decimal value of a roman string:
function roman2dec($str = '')
{
 // return false if not at least one letter is in the string:
  if(is_numeric($str)) return false;
 // define the roman figures:
  $roman = array(
  'm' => 1000,
  'd' => 500,
  'c' => 100,
  'l' => 50,
  'x' => 10,
  'v' => 5,
  'i' => 1
  );
 // convert the string to an array of roman values:
  for($i = 0; $i < strlen($str); $i++) 
  if(isset($roman[strtoupper($str[$i])]))
  $values[] = $roman[strtoupper($str[$i])];
 // calculate the sum of that array:
  $sum = 0;
  while($current = current($values))
  {
   $next = next($values);
   $next > $current ? $sum += $next - $current + 0 * next($values) : $sum += $current;
  }
 // return the value:
  return $sum;
}
// echo roman2dec(ix);  
?>

希望本文所述对大家的php程序设计有所帮助。