duanleixun2439 2015-03-14 13:52
浏览 12
已采纳

PHP使用不均匀的数字

I have two dynamic variables

$numberOfX = 2;

and

$numberOfY = 5;

The challenge for me is that I need to divide the number 5(numberOfY) between 2(numberOfX). That's an issue cause I will either through a calculation(divide) get a floating number like 2,5 or I can choose (ceil) to round it up but then I get 3(and totally it will be more then 5, namely 6).

I need a whole integers with no decimals. But still it can't be more or less then 5.

So ideally I Would like an array e.g with 3 and 2 in it. As it added will give 5.

How can I do this in PHP , remembering that numberOfX and numberOfY can be any number ?

  • 写回答

3条回答 默认 最新

  • douba7784 2015-03-14 14:08
    关注
    $numberOfX = 3;
    $numberOfY = 5;
    
    $result = array_fill(0, $numberOfX, (int) floor($numberOfY / $numberOfX)); 
    $i = 0;
    while (array_sum($result) !== $numberOfY) { 
        $result[$i++]++;
    }
    var_dump($result, array_sum($result));
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?