dongsheng8664 2016-06-27 14:21
浏览 45

试图检查PHP中的整数

The function below is trying to find whole numbers. But somehow I'm not doing this right as it shows every number to be whole (no digits after .)

$max_value % 1 should only return true is there is no rest value??

Can anyone help me, now every check gives 0 as result.

Hope I explain well what I mean

solution(30);

function solution($a){

 $sides_short = array();
 $sides_long  = array();
 $max_number  = $a/2;
 $total = $a;

 for($i=1;$i<=$max_number;$i++){
    $min_value = $i;
    $max_value = $a / $min_value;
    echo "loop values: ".$min_value." x ".$max_value."<br>";

    if($max_value % 1 == 0) {
        echo ($max_value % 1) ."<br>";
        echo "Aproved: (".$min_value." x ".$max_value.") $max_value % 1 = ".($max_value % 1)."<br><br>";
        $sides_short[] = $min_value; 
        $sides_long[] = $max_value;
    }
}

}

  • 写回答

2条回答 默认 最新

  • dongluan6784 2016-06-27 14:29
    关注

    You're using a modulo. That divides by that number and returns the remainder.

    $x = 3 % 2; // $x = 1
    

    3 goes into 2 once, and leaves a remainder of 1

    Anything divided by 1 is that number, with a remainder of 0. Therefore, this statement is always true.

    if($max_value % 1 == 0)
    

    Also, if you modulus a floating number, it will also be 0

    var_dump(8 % 1.5); // int(0)
    

    If you really need to modulus a float, use fmod

    var_dump(fmod(8, 1.5)); // float(0.5)
    
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行