在php中将整数转换为罗马数字

时间:2014-08-02 18:00:04

标签: php

我有一个输入文字名称=" number1" ,用户要求输入整数并进入confirm.php我想将我在index.php中输入的整数转换为罗马数字。如果我输入1,它将回显给我'我'如果2' II'等等。我迫不及待地想做作业。仍然不熟悉脚本新的PHP。无论如何,提前谢谢你

index.php:

<form  action="confirm_confirm.php" method="post">

  <input type="text" name="element1" >  

  <input type="text" name="number1" >

  <input type="text" placeholder="type" name="type1" >

  <input type="text" placeholder="metal type" name="metal_type" >

 <button type="submit" name="but" >Submit</button>
</form>   

并确认.php:

<?php session_start(); ?>   
<?php

  $element1 = $_POST['element1'];
  $number1 = $_POST['number1'];
  $type1 = $_POST['type1'];
  $metal_type = $_POST['metal_type'];

    if($metal_type == "transition")
        {

                echo "$element1";

        }
    ?> 

1 个答案:

答案 0 :(得分:0)

这是一个这样做的功能

<?php 
function romanNumerals($num){ 
    $n = intval($num); 
    $res = ''; 

    /*** roman_numerals array  ***/ 
    $roman_numerals = 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 ($roman_numerals as $roman => $number){ 
        /*** divide to get  matches ***/ 
        $matches = intval($n / $number); 

        /*** assign the roman char * $matches ***/ 
        $res .= str_repeat($roman, $matches); 

        /*** substract from the number ***/ 
        $n = $n % $number; 
    } 

    /*** return the res ***/ 
    return $res; 
} 

echo romanNumerals(23); 
?>