php 中使用小数计算不正确

Incorrect calculation using decimals in php

我有一些数组,用于保存乘法测验的数字。以下是一些示例:

if($level==8){
        $first=array(13,14,16,17,18,19);
        $second=array(9,10,11,12,13,14,15,16,17,18,19);}
        if($level==9){
        $first=array(23,19,46,87,98,39);
        $second=array(19,10,111,112,139,178,145,166,167,185,192);}
        if($level>9){
        $first=array(2.3,1.9,4.6,8.7,9.8,3.9);
        $second=array(1.9,10,11.1,11.2,13.9,17.8,14.5,16.6,16.7,18.5,19.2);}

这些数字用于计算一些放在按钮上的答案,用户必须点击正确的答案。

// the correct answer
        $b=rand(0,5);
        $c=rand(0,10);
        $f=$first[$b];
        $s=$second[$c];
        $d=$f*$s;
    // wrong answer no. 1
        $w1a=rand(0,5);
        $w1b=rand(0,10);
        $w1c=$first[$w1a];
        $w1d=$second[$w1b];
        $w1e=$w1c*$w1d;
        if ($w1e==$d){
            wronganswer1();
        }
    // wrong answer no. 2
    $w2a=rand(0,5);
        $w2b=rand(0,10);
        $w2c=$first[$w2a];
        $w2d=$second[$w2b];
        $w2e=$w2c*$w2d;
        if ($w2e==$d){
            wronganswer2();
        }

在POSTing的接收页面有检查用户是否确实得到了正确答案:

$b=$_POST["b"];
$c=$_POST["c"];
$subby=$_POST["sub"];
$d=$c * $b;
$score=$_SESSION["score"];
?>
</head>
        <body>
    <?php 

    if ($subby==$d){

    echo "<script>correct.play()</script>";}
    else{
        echo "<script>wrong.play()</script>";
        }

    ?>

    <?php

if ($subby==$d) {
    echo "Well done!";
    $_SESSION["score"]=$_SESSION["score"]+1;
    echo "<h3>The button you pressed said: ".$subby;
    echo "</h3><br><h2>";
    echo $b."x".$c."=".$subby;
    echo "</h2><br>";
    echo "<h3>Your streak is worth ".$_SESSION["score"];

} 
else {
    echo "<h1>No!<br>";
    $_SESSION["score"]=0;
    echo $b."x".$c."=".$d;
    echo "<br>";
    echo "Your streak has been reset to 0!</h1>";
}

现在,当我有整数时:没问题。但是小数导致了一个问题。我的代码告诉玩家正确的计算是错误的!

我花了一些时间来回显简单的十进制乘法并且输出是正确的(所以没有截断小数或类似的东西)...

为什么不准确?

我猜您正在以与整数相同的方式比较浮点数。

由于浮点数的性质,它不可能工作。

您无法检查浮点值是否相等,但您可以询问它们的绝对差异是否在您指定的容差范围内。这是显示我的意思的伪代码:

float x = 1.1;
float y = 1.2;
float tolerance = 1.0e-3;
if (abs(x-y) <= tolerance) {  // abs() is an absolute value function
   print "within tolerance"
} else {
   print "not within tolerance"
}

最后,我通过将 'comparator' 转换为字符串(参见代码的第一行),设法获得了预期的结果:

if ($subby==(string)$d) {
    echo "Well done!";
    $_SESSION["score"]=$_SESSION["score"]+1;
    echo "<h3>The button you pressed said: ".$subby;
    echo "</h3><br><h2>";
    echo $b."x".$c."=".$subby;
    echo "</h2><br>";
    echo "<h3>Your streak is worth ".$_SESSION["score"]; 

感谢所有帮助我找到“您无法比较浮动值”的conclusion/knowledge。