国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

php實現阿拉伯數字和羅馬數字相互轉換的方法

2024-09-04 11:42:41
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了php實現阿拉伯數字和羅馬數字相互轉換的方法,涉及php字符串操作的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下,本文實例講述了php實現阿拉伯數字和羅馬數字相互轉換的方法,分享給大家供大家參考,具體如下:

  1. <?php 
  2. // Function that calculates the roman string to the given number: 
  3. function dec2roman($f
  4.  // Return false if either $f is not a real number,  
  5.  //$f is bigger than 3999 or $f is lower or equal to 0:   
  6.   if(!is_numeric($f) || $f > 3999 || $f <= 0) return false; 
  7.  // Define the roman figures: 
  8.   $roman = array
  9.   'M' => 1000, 
  10.   'D' => 500, 
  11.   'C' => 100, 
  12.   'L' => 50, 
  13.   'X' => 10, 
  14.   'V' => 5, 
  15.   'I' => 1 
  16.   ); 
  17.  // Calculate the needed roman figures: 
  18.   foreach($roman as $k => $v
  19.   if(($amount[$k] = floor($f / $v)) > 0) 
  20.   $f -= $amount[$k] * $v
  21.  // Build the string: 
  22.   $return = ''
  23.   foreach($amount as $k => $v
  24.   { 
  25.    $return .= $v <= 3 ? str_repeat($k$v) : $k . $old_k
  26.    $old_k = $k;   
  27.   } 
  28.  // Replace some spacial cases and return the string: 
  29.   return str_replace(array('VIV','LXL','DCD'),array('IX','XC','CM'),$return); 
  30. // echo dec2romen(1981); 
  31. // Function to get the decimal value of a roman string: 
  32. function roman2dec($str = ''
  33.  // Return false if not at least one letter is in the string: 
  34.   if(is_numeric($str)) return false; 
  35.  // Define the roman figures: 
  36.   $roman = array
  37.   'M' => 1000, 
  38.   'D' => 500, 
  39.   'C' => 100, 
  40.   'L' => 50, 
  41.   'X' => 10, 
  42.   'V' => 5, 
  43.   'I' => 1 
  44.   ); 
  45.  // Convert the string to an array of roman values: 
  46.   for($i = 0; $i < strlen($str); $i++)  
  47.   if(isset($roman[strtoupper($str[$i])])) 
  48.   $values[] = $roman[strtoupper($str[$i])]; 
  49.  // Calculate the sum of that array: 
  50.   $sum = 0; 
  51.   while($current = current($values)) 
  52.   { 
  53.    $next = next($values); 
  54.    $next > $current ? $sum += $next - $current + 0 * next($values) : $sum += $current
  55.   } 
  56.  // Return the value: 
  57.   return $sum
  58. // echo roman2dec(IX);   
  59. ?>

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 金坛市| 西乌珠穆沁旗| 乌拉特中旗| 房产| 新乐市| 海原县| 南投市| 平昌县| 车致| 厦门市| 清河县| 香河县| 双江| 宁乡县| 玉山县| 广西| 长沙市| 阜南县| 五原县| 金川县| 昌江| 阳春市| 扎兰屯市| 沐川县| 沁水县| 屯留县| 阳泉市| 房产| 炉霍县| 嘉黎县| 阳朔县| 沂水县| 齐齐哈尔市| 监利县| 永嘉县| 察雅县| 泾川县| 久治县| 文昌市| 凤山县| 昌图县|