双?整数? - PHP

时间:2013-12-04 00:15:50

标签: php

以下代码生成两个随机十进制值,然后将它们减去以获得$c

$a = mt_rand(5, 75);
$b = mt_rand(5, 75);
$adjuster = mt_rand(2, 20);

do {
    $decimal_selector = mt_rand(1, 6);
    if ($decimal_selector == 1) {
        $a = $a / 10;
        $b = $b / 10;
    }
    if ($decimal_selector == 2) {
        $a = $a / 10;
        $b = $b / 100;
    }
    if ($decimal_selector == 3) {
        $a = $a / 100;
        $b = $b / 10;
    }
    if ($decimal_selector == 4) {
        $a = $a / 100;
        $b = $b / 100;
    }
    if ($decimal_selector == 5) {
        $a = $a / 1000;
        $b = $b / 1000;
    }
    if ($decimal_selector == 6) {
        $a = $a / 1000;
        $b = $b / 100;
    }

    if($b < $a)
        $b = $b + ($a - $b) + $adjuster;

    $c = $b - $a;
} while((is_int($a) == true && is_int($b) == true) || is_int($c) == true);

do-while循环尝试确保$a$b都不是整数,并且$c不是整数。但我不断得到$c实际上是整数的时间。

如果我使用gettype,我会一直说$c是“双倍”。为什么,$c最终会出现7

编辑: 我一直在从下面的代码中获得随机无限循环。有什么想法吗?

        do{
            $a = mt_rand(5, 75);
            $b = mt_rand(5, 75);
            $adjuster = mt_rand(2, 20);

            $decimal_selector = mt_rand(1, 6);
            if ($decimal_selector == 1){
                $a = $a / 10;
                $b = $b / 10;
            }
            if ($decimal_selector == 2){
                $a = $a / 10;
                $b = $b / 100;
            }
            if ($decimal_selector == 3){
                $a = $a / 100;
                $b = $b / 10;
            }
            if ($decimal_selector == 4){
                $a = $a / 100;
                $b = $b / 100;
            }
            if ($decimal_selector == 5){
                $a = $a / 1000;
                $b = $b / 1000;
            }
            if ($decimal_selector == 6){
                $a = $a / 1000;
                $b = $b / 100;
            }

            if($b < $a){
                $b = $b + ($a - $b) + $adjuster;
            }

            $c = $b - $a;

            if(intval($c) == $c) {
                $c_is_int = 1;
            } else {
                $c_is_int = 0;
            }

echo intval($c) . '<br>';
echo $c_is_int . '<br>';
echo $c . '<br><br>';
        } while($c_is_int == 1);

enter image description here

2 个答案:

答案 0 :(得分:4)

双减去一个double会产生一个double,即使该数字是一个整数

$c = (int) ($b - $a);

答案 1 :(得分:3)

做这样的事情,看看$c是否是整数(可能存储为双数):

if(intval($c) == $c) {
    echo "I'm a whole number";
}

见这里:http://3v4l.org/ubPK4