[Solved] Pascal Div function on PHP

Discussion in 'Off-Topic' started by Kenn Fatt, Jun 12, 2017.

  1. Kenn Fatt

    Kenn Fatt Slime

    Messages:
    82
    GitHub:
    kennfatt
    Hello,

    If you have experienced with Pascal language, we know that mod and div function, or you can see my example here:

    Code:
    n:= 5 mod 2; // 1
    m:= 5 div 2; // will return to 2, 2x2 = 4 + 1 = 5.
    
    x:= 8 div 2; // will return to 4, 2x4 = 8
    y:= 9 div 1; // will return to 9, 1x9 = 9
    
    You can see reference here:
    http://wiki.freepascal.org/Div

    And now, There is alternative or a same function on PHP? Thanks.
     
  2. Kenn Fatt

    Kenn Fatt Slime

    Messages:
    82
    GitHub:
    kennfatt
    Lol its same like (int) 5 / 2
     
  3. SOFe

    SOFe Administrator Staff Member PMMP Team Poggit Admin

    Messages:
    1,968
    GitHub:
    sof3
    According to Free Pascal Wiki:
    PHP provides the % operator, which is equivalent to mod. It will implicitly cast the operands to integers before execution.

    PHP also provides /, but it manages types like this: for the operation "$a % $b",
    • If $a is int and $b is int and $a is divisible by $b ("divisible" is defined as "$b multiplied by an integer yields $a"), the quotient is returned as an int.
    • If $a is int and $b is int and $a is not divisible by $b, the quotient is returned as a float.
    • If $a or $b or both of them is float, the result is always a float, even if the float represents an integer (i.e. even if `$float == (int) $float` is true but `$float === (int) $float` is false)

    The integer division (div) in Pascal simply takes the floor value of the quotient, which is equivalent to a float cast to an int in PHP. Therefore, always putting (int) for the division expression, e.g. `(int) (7 / 2)` will work.
    Note that since the division operator in PHP, `/`, has lower precedence than the type casting operator `(int)`, you must parenthesize the division expression.
     
  4. Kenn Fatt

    Kenn Fatt Slime

    Messages:
    82
    GitHub:
    kennfatt
    yeah, i missed that "Div" means Division :D
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.