【问题标题】:PHP: Why multiplying by "1E3" returns double and not int?PHP:为什么乘以“1E3”返回double而不是int?
【发布时间】:2019-09-10 08:59:44
【问题描述】:

我有以下代码:

$waitTimeInMs = random_int(500, 1000);
// 1E3 = 10 to the power of 3 = 1000
echo gettype($waitTimeInMs) .'|'.gettype($waitTimeInMs * 1E3) . '|' . gettype($waitTimeInMs * 1000) .'|' . $waitTimeInMs * 1E3;

这将返回integer|double|integer|759000

所以,实际上:

  • random_int() 返回int
  • 乘以1E3 返回double
  • 乘以1000 返回int

那么,如果1000 = 1E3,为什么乘以1E3 会返回一个double 而不是int

【问题讨论】:

    标签: php int double exponent exponentiation


    【解决方案1】:

    你的假设是错误的:

    // 1E3 = 10 to the power of 3 = 1000
    

    1E3+1.000E3 的缩写形式。根据定义,它是科学计算机记数法中的浮点数:

    // 1.23E4   => 1.23 * 10^4
    // computer => scientific notation of a real number
    

    顺便说一句:0.123e5 === 1.23e4 === 12.3e3 === 123e2 === 12300e0 === 12300.0

    【讨论】:

      【解决方案2】:

      指数数存储为 double .. 因为 php 不会更改正指数或负指数的数据类型

      https://www.php.net/manual/en/language.types.float.php
      

      数据类型相同

      $c = 7E-10;
      

      $c = 7E+10;
      

      但第一个通常是浮点数

      【讨论】:

      • 为什么将它们存储为浮点数比将它们存储为整数更好?
      • 因为无法在整数中存储负指数(例如 7E-3 = 0,003)..
      猜你喜欢
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      相关资源
      最近更新 更多