循环无法正常工作(浮点数和整数问题?)-PHP [英] Loop not working correctly (floats and integer issue?) -- PHP

查看:48
本文介绍了循环无法正常工作(浮点数和整数问题?)-PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码生成两个随机的十进制值,然后将它们相减得到$c.

The code below generates two random decimal values, then subtracts them to get $c.

do-while循环试图确保$c不会是整数.但是我不断得到$c实际上是整数的时间.

The do-while loop is trying to ensure that $c will not be a whole number. But I keep getting times where $c actually is a whole number.

        do{
            unset($a);
            unset($b);
            unset($c);
            unset($adjuster);
            unset($c_is_int);

            $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 $a . '<br><br>';
echo $b . '<br><br>';
echo intval($c) . '<br>';
echo $c_is_int . '<br>';
echo $c . '<br><br>';
        } while($c_is_int == 1);

所附图像显示了这些失败时间之一的结果.有什么想法可以解决这个问题吗?

The attached image shows the results of one of these failing times. Any ideas on where this is going wrong?

推荐答案

为什么不检查数字是否为小数?

Why not check to see if the number has a decimal?

$c = 123.456;

if(strpos((string) $c, '.') !== FALSE) {
    // is decimal/float/double
}

您也可以只检查它是否为整数

You can also just check to see if it's an int

if(is_int($c))

这篇关于循环无法正常工作(浮点数和整数问题?)-PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆