【问题标题】:What are the significant differences with these two PHP equations?这两个 PHP 方程有什么显着差异?
【发布时间】:2014-01-10 11:04:31
【问题描述】:

工作示例:http://ideone.com/Ond6PY

您有两个变量,即$a = 5$b = 9

这两个语句在数学上的主要区别是什么?

floor(floor($a / $b) - .5); //output: -1

(int)((int)($a / $b) - .5); //output: 0

【问题讨论】:

  • 猜测:floor 向下舍入(负无穷大),(int) 截断(向 0 舍入)。
  • (int) 是类型转换,而不是函数!
  • this question 的热门回答解释了这一点。与上面zch的评论相同。

标签: math integer floor


【解决方案1】:

注意你的表达部分的四舍五入。

5/9 的除法是

$a / $b = 5 / 9 = 0.555555556

http://php.net/manual/en/function.floor.php

floor(1.5) = 1
floor(-1.5) = -2

然后

floor(floor($a / $b) - .5) = floor(floor(0.555555556)) = floor(0 - .5) = floor(-.5) = -1

和第二种情况 见http://www.php.net/intval

(int) 4.32 = 4

然后

(int)((int)($a / $b) - .5) = (int)((int)(0.555555556) - .5) = (int)(0 - .5) = int(-0.5) = 0;

【讨论】:

  • 错了。这不是 intval,这是类型转换:看这里!:php.net/manual/de/language.types.type-juggling.php
  • @Sebi2020 对,即使这不是“intval”,舍入算法也是一样的。我使用该链接是因为 php.net 上有舍入的解释。如果您有更好的答案,请编辑答案。
  • 显然我不是。我的回答得到了两次反对。
【解决方案2】:

(int) 是一个类型转换,你会得到一个整数,例如2、3、5 等楼层向下舍入。

所以使用(int)((int) 5 / 9)-0.5) 你会得到:

0 - 0 (0.56666666) = 0

(int) 不是函数!看这里:Type Casting - PHP DOC

【讨论】:

    猜你喜欢
    • 2015-03-27
    • 2014-12-22
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多