PHP计算不正确

时间:2016-03-12 12:10:19

标签: php

我是PHP的初学者,我想创建一个将十进制数转换为十六进制数的程序。 (实际上我想将我的颜色十进制值转换为十六进制值)但是,它无法正常工作。例如,当我按下转换按钮时,使用以下参数:red = 98 blue = 123 green = 54 它会生成以下结果:

Red : Green : Blue : B

我不明白错误是什么。

这是我的源代码:

<html>
<head>
    <title>Convert Decimal Number to Hexadecimal Number</title>
<form method="POST" action="index.php" >
    Red  :  <input type="text" name="red" /> <br />
    Green:  <input name="green" type="text" /> <br />
    Blue :  <input name="blue" type="text" /> <br />
    <input type="submit" value="Calculate!" /> <br />
</form>
</head>
<body>
    <?php
    $completely="";
    if ($_POST['red']==""){
        exit();
    }
    function subcalculate($valuetoconvert){
        if ($valuetoconvert>9){
            switch ($valuetoconvert){
                case 10:
                    $valuetoconvert=A;
                    break;
                case 11:
                    $valuetoconvert=B;
                    break;
                case 12:
                    $valuetoconvert=C;
                    break;
                case 13:
                    $valuetoconvert=D;
                    break;
                case 14:
                    $valuetoconvert=E;
                    break;
                case 15:
                    $valuetoconvert=F;
                    break;
            }
            return $valuetoconvert;
        }
    }
    function dectohexcal($color,$colorname){
        $bir=subcalculate(($color-($color%16))/16);
        $iki=subcalculate($color%16);
        if ($bir==0){
            echo "$colorname :    $iki <br />";
            $completely=$completely+$iki;
        }else{
            echo "$colorname :    $bir$iki <br />";
            $completely=$completely+$bir+$iki;
        }

    }
    dectohexcal($_POST['red'], "Red");
    dectohexcal($_POST['green'], "Green");
    dectohexcal($_POST['blue'], "Blue");
    echo "<br />$completely";
    ?>

</body>

1 个答案:

答案 0 :(得分:1)

你只需要使用     dechex() php4 +提供的功能。

<?php
echo "Red: ".dechex($_POST['red']) . "\n";
echo "Green: ". dechex($_POST['green'])."\n";
echo "Blue: ".dechex($_POST['blue']);
?>

这样可以完成你的工作而无需重新发明轮子。

相关问题