douya5194 2013-12-19 12:15
浏览 14
已采纳

在PHP中捕获高于或低于整数值的值[关闭]

I need to have a variable always changed to be within a certain range (0-5), working on rounds. For instance, if the variable hits 6, it should be changed to 0; if it hits -1, it should be changed to 5. Here's my pseudo, any ideas?

function get_further_letter($index = 5, $number = 3, $direction = "encode") {
    $count = 5;
    switch ($direction) 
    {
    case "encode":
        $index = $index + $number; //pushes the value of index to 8
        break;
    }
    // Start my attempt
    while ($index > $count)
    {
        $index = $index - $count;
    }
    // End my attempt
    return $index;
}

>> get_further_letter(5, 3); // 5 + 3 = 8, 8 is 1r3, so keep r3 as 0, 1, 2
2
>> get_further_letter(5, 4); // 5 + 4 = 9, 9 is 1r4, so keep r4 as 0, 1, 2, 3
3
>> get_further_letter(5, -7); // 5 + -7 = -2, -2 is -1r-2, so keep r-2 as 0, 1, 2, 3
4

Sorry for being vague, I'm very confused about how to get this to work, so it's a little difficult to articulate my requirements.

I got -2 for the last example as in my case specifically the value will be an array index. I'm not sure if this is actually going to happen.

  • 写回答

1条回答 默认 最新

  • dongye8110 2013-12-19 13:11
    关注

    The generic function that will keep a value within the range of [0 .. n) is this:

    function fn($x, $n)
    {
        return ($x % $n + $n) % $n;
    }
    

    The double modulo is to deal with negative numbers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算